<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\api\controller\KbxOrder;
use app\api\controller\OssController;
use app\api\controller\Common;
use app\wap\controller\Gdimg;
use \think\Db;
use \think\Cookie;
use app\admin\model\Goods as G;
use app\api\model\Fareharbor as F;
use app\api\controller\FareGoods as FApi;
use app\api\controller\Viator as Viator;
use app\api\controller\ExportExcel;
use app\api\controller\KbxOther;
use app\api\controller\Poi;
use think\db\Expression;
use think\Exception;
use think\log;
use think\Cache;
use app\api\model\Standard as SDModel;
use app\api\model\Goods as GModel;
use app\admin\model\Standardtags as StandardtagsModel;
use app\wap\controller\Notify as Msg;
use app\api\model\GroupToursLine as GT;
use app\admin\controller\Product as ProController;
use app\api\controller\Esapi;
use app\api\model\HotelSpu;
use think\Request;

class Goods extends User
{
    //更新价格配置状态
    public function updPersonPriceStatus(){
        $goods_ids = db('personday')->field('goods_id')->group("goods_id")->select();
        $goods_ids_arr = array_column($goods_ids,'goods_id');
        $goods_ids = implode(",",$goods_ids_arr);
        $sql = 'select p.goods_id,FROM_UNIXTIME(g.starttime,"%Y-%m-%d") as starttime,min(p.time) as min_time,max(p.time) as max_time,FROM_UNIXTIME(g.endtime,"%Y-%m-%d") as endtime from tplay_personday p left join tplay_goods g on p.goods_id=g.goods_id where source_id=0 and p.goods_id in ('.$goods_ids.') group by goods_id HAVING max_time >= endtime';
        $new_goods = db::query($sql);
        $new_goods = array_column($new_goods,'goods_id');
        $new_arr= array_diff($goods_ids_arr,$new_goods);
        if(!empty($new_arr)){
            $where['goods_id'] = ['in',$new_arr];
            db('goods')->where($where)->update(['update_selltime'=>'1']);
        }
        return json(['code'=>200,'msg'=>'ko','data'=>count($new_arr)]);
    }

    //加載頁面
    public function batchedit(){
        $goods_id= input('id');
        $goods = db("goods")->find($goods_id);
        $starttime = $goods['starttime']>time()?$goods['starttime']:time();
        $starttime = date("Y-m-d",$starttime);
        $endtime = date("Y-m-d",$goods['endtime']);
        $personday = db("personday")->where(["goods_id"=>$goods_id,'time'=>['between',[$starttime,$endtime]]])->select();
        //按天封装数据

        $data = [];
        foreach ($personday as $value){
            $data[$value['time'].",".$value['specs_id']][] = $value;
        }
        $this->assign('goods',$goods)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime);
        return $this->fetch();
    }

    //获取特定时间范围内的价格设置
    public function personprice(){
        $goods_id = input('id');
        $sdate =	input('sdate');
        $edate =	input('edate');
        $personday = db("personday")->where(["goods_id"=>$goods_id,'time'=>['between',[$sdate,$edate]]])->select();
        //按天封装数据

        $data = [];
        foreach ($personday as $value){
            $data[$value['time'].",".$value['specs_id']][] = $value;
        }

        return json(['code'=>200,'msg'=>'ko','data'=>$data]);
    }

    //查詢套餐
    public function werk(){
        $goods_id =	input('id');
        $list =	db('specs')->where('goods_id',$goods_id)
            ->where('specs_types',1)
            ->where('specs_status',1)
            ->limit(5)
            ->select();
        if(empty($list)){
            return json(['code'=>-1,'data'=>$list]);
        }else{
            return json(['code'=>200,'data'=>$list]);
        }
    }

    //查詢人群
    public function pos(){
        $specs_id =	input('specs_id');
        $list =	db('person')->where('specs_id',$specs_id)
            ->where('person_status',1)
            ->select();
        return json($list);


    }

    //提交选项卡
    public function addperson(){
        if(request()->isPost()){
            $post =  request()->post();

            if(empty($post['dates'])) return $this->error('参数为空');
            $shu =json_decode($post['dates'],true);
            Db::startTrans();
            $b = 0;
            try{
                $where  = [];
                $dats   = [];
                $price = [];
                $add_data = [];
                $goodsinfo = db("goods")->field("starttime,endtime")->where("goods_id",$post['goods'])->find();
                foreach ($shu as $v){
                    $v['goods_id']=$post['goods'];
                    $where['person_id'] = $v['person_id'];
                    $where['specs_id']  = $v['specs_id'];
                    $where['time']      = $v['time'];
                    $where['goods_id']  = $v['goods_id'];
                    $price []=$v['person_price'];
                    $personday = db('personday')->where($where)->find();
                    if (false == $personday || empty($personday)){
                        $add_data[] = $v;
                    }else{
                       $b = 1;
                       if($v['person_price']!=$personday['person_price'] ||
                        $v['person_num']!=$personday['person_num'] ||
                        $v['minorder_num']!=$personday['minorder_num'] ||
                        $v['person_name']!=$personday['person_name']
                        ){
                            Db::name('personday')->where($where)->update($v);
                       }
                    }
                }

                if(!empty($add_data)){
                    $b = 0;
                    Db::name('personday')->insertAll($add_data);
                }
                //更新商品价格区间
                $min = min($price);
                $max = max($price);
                //获取目前商品的最低价和最高价
                $goods_stime = date("Y-m-d",$goodsinfo['starttime']);
                $goods_etime = date("Y-m-d",$goodsinfo['endtime']);
                $price_data = (new G())->personDayMaxAndMinPrice($post['goods'],$goods_stime,$goods_etime);
                if(!empty($price_data) && $price_data['min']<=$price_data['max']){
                    $min = $min <= $price_data['min']?$min:$price_data['min'];
                    $max = $max >= $price_data['max']?$max:$price_data['max'];
                }
                $price_section = $min.'~'.$max;
                //更新价格区间和价格套餐字段
                db('goods')->where('goods_id',$post['goods'])->update([
                    'price_section'=>$price_section,
                    'update_selltime'=>'0',
                    'min_price'=>$min,
                    'max_price'=>$max
                ]);
                //初始化当前商品日历缓存
                cache($post['goods'].'rl',null);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->success($e->getMessage());
            }
            if ($b==0){
                return $this->success('添加成功');
            }else{
                return $this->success('修改成功');
            }
        }else{
            $this->error('请求非法');die;
        }
    }

    /**
     * 列表首页
     */
    public function index()
    {
        $where=[];
        $exportFlag=request()->param('exportFlag');//是否为导出

        $post = request()->post();
        if($this->request->isPost()){
            //把条件写入缓存
            Cookie::set('wheres_goods',$post);
        }else{
            $idss=$this->request->param('page');
            if(!empty($idss) || isset($exportFlag)){
                $post = Cookie::get('wheres_goods');
            }else{
                Cookie::set('wheres_goods',$post);
            }
        }
        if(!empty($post['keywords'])){
            $where['a.goods_id|a.goods_name|a.goods_tcode'] = ['like',trim($post['keywords']).'%'];
        }
//        if (isset($post['goods_id']) and $post['goods_id'] > 0) {
//            $where['a.goods_id'] = $post['goods_id'];
//        }
//        if (isset($post['goods_name']) and $post['goods_name'] !='') {
//            $where['a.goods_name']=['like','%'.trim($post['goods_name']).'%'];
//        }
//        if (isset($post['goods_tcode']) and $post['goods_tcode'] !='') {
//            $where['a.goods_tcode']=['like','%'.trim($post['goods_tcode']).'%'];
//        }
        if (isset($post['goods_status']) and $post['goods_status'] > 0) {
            $where['a.goods_status'] = $post['goods_status'];
        }
        if (isset($post['city_id']) and $post['city_id']>0){
            $where['a.city_id'] = $post['city_id'];
        }
        if (isset($post['classify_id']) and $post['classify_id']>0){
            $where['a.classify_id'] = $post['classify_id'];
        }
        if (isset($post['supplier_id']) and $post['supplier_id']!==''){
            $where['a.supplier_id'] = $post['supplier_id'];
        }
        //订单类型
        if (isset($post['orderType']) && $post['orderType']!==''){
            $where['a.orderType'] = $post['orderType'];
        }
        //价格设置
        if (isset($post['updSellTime']) && $post['updSellTime']!==''){
            $where['a.update_selltime'] = (string)$post['updSellTime'];
        }
        //tob是否上架
        if (isset($post['isTob']) && $post['isTob']!==''){
            if($post['isTob']==1){
                $where['st.show_toB'] = 1;
            }elseif($post['isTob']==2){
                $exp =new \think\db\Expression('is null or st.show_toB = 0');
                $where['st.show_toB'] = ['exp',$exp];
            }
        }

        $search_page = 10;
        //导出查询条件
        if($exportFlag==1){
            $search_page = 10000;
        }
        //show = 1 自营商品
        $subQuery = db('goods')
            ->where('show',1)
            ->buildSql();

        $date= (new G())->table($subQuery.' a')->where($where)
            ->field('a.*,c.name,g.tag_name,st.show_toB')
            ->join('city c','a.city_id=c.id','left')
            ->join('goodstag g','a.goodstag_id=g.tag_id','left')
            ->join('standard st','a.goods_id=st.goods_id','left')
            ->order('a.goods_id desc')->paginate($search_page);

        $classify=db('classify')->where('classify_status',1)->select();
        $city= db('city')->where('deleted',0)->where('type','CITY')->select();
        $where_poi['typeid']=8;
        $where_poi['deleted']=0;
        $goodssoure=Db::name('poi')->where($where_poi)->order('create_time desc')->select();


        foreach ($date as $k=>$v) {
            $product_id = '';
            $product_exists = 0;
            $product_price_exists = 0;

            //存在产品时
            if(!empty($v['goods_tcode']) && $v['goods_tcode']!==''){
                $product = db("product")->where("item_num",$v['goods_tcode'])->field("id")->find();
                if(!empty($product)){
                    $product_id = $product['id'];
                    $product_exists = 1;
                    $dailyprice = db("product_dailyprice")->where("product_id",$product_id)->find();
                    if(!empty($dailyprice)){
                        $product_price_exists = 1;
                    }else{
                        $dailyprice = db("product_base_dailyprice")->where("product_id",$product_id)->find();
                        if(!empty($dailyprice)){
                            $product_price_exists = 1;
                        }
                    }
                }
            }

            $date[$k]['product_id'] = $product_id;
            $date[$k]['product_exists'] = $product_exists;
            $date[$k]['product_price_exists'] = $product_price_exists;
        }

        $this->assign('goodssoure',$goodssoure);
        $this->assign('liebiao',$date);
        $this->assign('classify',$classify);
        $this->assign('city',$city);
        $this->assign('where',$post);
        //商品的订单类型
        $orderType = array(
            array('type'=>'Ticket_FIT','name'=>'地接社标品'),
            array('type'=>'Ticket_POI','name'=>'门票类产品'),
            array('type'=>'Hotel','name'=>'酒店'),
            array('type'=>'Custom','name'=>'定制产品'),
            array('type'=>'Vehicle','name'=>'用车'),
            array('type'=>'Ticket_AIR','name'=>'机票'),
            array('type'=>'Rental_Device','name'=>'物品购买/租赁'),
            array('type'=>'Other','name'=>'其它'),
            array('type'=>'Price_Gap','name'=>'补差价'),
            array('type'=>'Self_Drive','name'=>'自驾游'),
            array('type'=>'Personal_Tailor','name'=>'私人定制服务'),
            array('type'=>'Subscription','name'=>'代订服务'),
        );
        $this->assign('orderType',$orderType);

        //供应商
        list($supplier,$supplierNameArr) = (new Product())->getSupplierList();
        $this->assign('supplier',$supplier);

        //导出方法
        if($exportFlag==1){
            $orderTypeArr = array(
                'Ticket_FIT'=>'地接社标品',
                'Ticket_POI'=>'门票类产品',
                'Hotel'=>'酒店',
                'Custom'=>'定制产品',
                'Vehicle'=>'用车',
                'Ticket_AIR'=>'机票',
                'Rental_Device'=>'物品购买/租赁',
                'Other'=>'其它',
                'Price_Gap'=>'补差价',
                'Self_Drive'=>'自驾游',
                'Personal_Tailor'=>'私人定制服务',
                'Subscription'=>'代订服务',
            );
            $dataArr = array();
            $ExportExcel = new ExportExcel();
            foreach ($date as $k=>$v) {
                $data = array();
                $data['goods_id'] = $v['goods_id'];
                $data['goods_name'] = $v['goods_name'];
                $data['goods_tcode'] = $v['goods_tcode'];
                $data['tag_name'] = $v['tag_name'];
                $data['orderType'] = isset($orderTypeArr[$v['orderType']])?$orderTypeArr[$v['orderType']]:'';
                $data['name'] = $v['name'];
                $data['starttime'] = date("Y-m-d",$v['starttime']);
                $data['endtime'] = date("Y-m-d",$v['endtime']);
                $dataArr[] = $data;
            }
            $table_head = array("商品编号","商品名称","行程编码","商品类型","订单类型","城市","开始时间","结束时间");
            $ExportExcel->exportExcel($dataArr, $table_head, "商品列表");
        }else{
            return $this->fetch();
        }
    }

    public function othergoods(){
        $where=[];
        $exportFlag=request()->param('exportFlag');//是否为导出

        if($this->request->isPost()){
            $post = request()->post();
            //默认选择售卖中
            $post['goods_status'] = !isset($post['goods_status']) ? 1 : $post['goods_status'];
            //把条件写入缓存
            Cookie::set('otherlist',$post);
        }else{
            $idss=$this->request->param('page');
            if(!empty($idss) || isset($exportFlag)){
                $post = Cookie::get('otherlist');
            }else{
                //默认选择售卖中
                $post['goods_status'] = 1;
                Cookie::set('otherlist',$post);
            }
        }
        if(!empty($post['keywords'])){
            $where['a.goods_id|a.code|a.goods_name|a.goods_englishname'] = ['like',trim($post['keywords']).'%'];
        }

        if (isset($post['goods_status']) and $post['goods_status'] > 0) {
            $where['a.goods_status'] = $post['goods_status'];
        }
        if (isset($post['accidentDrop']) and $post['accidentDrop'] > 0) {
            $where['a.accidentDrop'] = $post['accidentDrop'];
        }

        if (isset($post['classify_id']) and $post['classify_id']>0){
            $where['a.classify_id'] = $post['classify_id'];
        }
        if (isset($post['team_id']) and $post['team_id']>0){
            $where['a.team_id'] = $post['team_id'];
        }
        if (isset($post['isquestion']) and $post['isquestion']>0){
            $where['a.isquestion'] = $post['isquestion'];
        }
        //是否需要更新
        if (isset($post['isupdated']) and $post['isupdated']>0){
            $where['a.isupdated'] = $post['isupdated'];
        }
        //Api接口类型
        if (isset($post['api_type']) && $post['api_type']!==''){
            $where['a.api_type'] = $post['api_type'];
        }
        //订单类型
        if (isset($post['orderType']) && $post['orderType']!==''){
            $where['a.orderType'] = $post['orderType'];
        }

        //tob是否上架
        if (isset($post['isTob']) && $post['isTob']!==''){
            if($post['isTob']==1){
                $where['st.show_toB'] = 1;
            }elseif($post['isTob']==2){
                $exp =new \think\db\Expression('is null or st.show_toB = 0');
                $where['st.show_toB'] = ['exp',$exp];
            }
        }

        //确认类型
        if (isset($post['confirm_type']) && $post['confirm_type']>0){
            if($post['confirm_type']==1){//立即确认
                $where['bookingEngine'] = array('in','UnconditionalBE,FreesaleBE');
            }elseif($post['confirm_type']==2){
                $where['bookingEngine'] = 'FreesaleOnRequestBE';
            }elseif($post['confirm_type']==3){
                $where['bookingEngine'] = 'DeferredCRMBE';
            }
            $this->assign('confirm_type',$post['confirm_type']);
        }
        if (isset($post['city_id']) and $post['city_id']>0){
            $id=$post['city_id'];
            $res_city=Db::name('city')->where('id',$id)->find();
            $where['a.city_id'] = [['eq',$res_city['id']],['eq',$res_city['destid']],'OR'];
        }

        $search_page = 10;
        //导出查询条件
        if($exportFlag==1){
            $search_page = 10000;
        }
        //show = 2 viator商品
        $subQuery = db('goods')
            ->where('show',2)
            ->buildSql();
        //获取符合条件的goods_id
//        $goods_ids = (new G())->table($subQuery.' a')->where($where)
//            ->field('a.goods_id')
//            ->join('standard st','a.goods_id=st.goods_id','left')
//            ->join('standardtags stag','st.id=stag.sid','left')
//            ->where('stag.tagid is not null')
//            ->group('a.goods_id')->select();
//        var_dump(db()->getLastSql());exit;
//        if(!empty($goods_ids)){
//            $goods_ids_str = implode(',',array_unique(array_column($goods_ids,'goods_id'))) ;
//            $having_where = '(goods_id in ('.$goods_ids_str.') and tagid is not null) or (goods_id not in ('.$goods_ids_str.') and tagid is null)';
//        }else{
//            $having_where = '1=1';
//        }
        $date= (new G())->table($subQuery.' a')->where($where)
            ->join('city c','a.destid=c.destid','left')
            ->join('goodstag g','a.goodstag_id=g.tag_id','left')
            ->join('standard st','a.goods_id=st.goods_id','left')
            ->field('a.*,c.name,g.tag_name,st.show_toB')
            ->order('a.updatetime desc')->paginate($search_page);
        $classify=db('classify')->where('classify_status',1)->select();
        $city= db('city')->where('deleted',0)->where('type','CITY')->select();
        $where_poi['typeid']=8;
        $where_poi['deleted']=0;
        $goodssoure=Db::name('poi')->where($where_poi)->order('create_time desc')->select();

        foreach ($date as $k=>$v) {
            if($v['bookingEngine']=='FreesaleBE' || $v['bookingEngine']=='UnconditionalBE'){
                $date[$k]['confirm_type'] = 1;
            }elseif($v['bookingEngine']=='FreesaleOnRequestBE'){
                $date[$k]['confirm_type'] = 2;
            }else{
                $date[$k]['confirm_type'] = 3;
            }

            //查询是否存在FAQ
            $faq_flag = 0;
            $faq = db("faq")
                ->where("groupid",$v['goods_id'])
                ->where("typeid",3)
                ->where("deleted",0)
                ->find();
            if(!empty($faq)){
                $faq_flag = 1;
            }

            $date[$k]['faq_flag'] = $faq_flag;
        }

        $this->assign('goodssoure',$goodssoure);
        $this->assign('liebiao',$date);
        $this->assign('classify',$classify);
        $this->assign('city',$city);


        $this->assign('where',$post);

        //商品的订单类型
        $orderType = array(
            array('type'=>'Ticket_FIT','name'=>'地接社标品'),
            array('type'=>'Ticket_POI','name'=>'门票类产品'),
            array('type'=>'Hotel','name'=>'酒店'),
            array('type'=>'Custom','name'=>'定制产品'),
            array('type'=>'Vehicle','name'=>'用车'),
            array('type'=>'Ticket_AIR','name'=>'机票'),
            array('type'=>'Rental_Device','name'=>'物品购买/租赁'),
            array('type'=>'Other','name'=>'其它'),
            array('type'=>'Price_Gap','name'=>'补差价'),
            array('type'=>'Self_Drive','name'=>'自驾游'),
            array('type'=>'Personal_Tailor','name'=>'私人定制服务'),
            array('type'=>'Subscription','name'=>'代订服务'),
        );
        $this->assign('orderType',$orderType);

        //导出方法
        if($exportFlag==1){
            $orderTypeArr = array(
                'Ticket_FIT'=>'地接社标品',
                'Ticket_POI'=>'门票类产品',
                'Hotel'=>'酒店',
                'Custom'=>'定制产品',
                'Vehicle'=>'用车',
                'Ticket_AIR'=>'机票',
                'Rental_Device'=>'物品购买/租赁',
                'Other'=>'其它',
                'Price_Gap'=>'补差价',
                'Self_Drive'=>'自驾游',
                'Personal_Tailor'=>'私人定制服务',
                'Subscription'=>'代订服务',
            );
            $dataArr = array();
            $ExportExcel = new ExportExcel();
            foreach ($date as $k=>$v) {
                $data = array();
                $data['goods_id'] = $v['goods_id'];
                $data['code'] = $v['code'];
                $data['goods_name'] = $v['goods_name'];
                $data['tag_name'] = $v['tag_name'];
                $data['orderType'] = isset($orderTypeArr[$v['orderType']])?$orderTypeArr[$v['orderType']]:'';
                $data['name'] = $v['name'];
                $data['price'] = !empty($v['price'])?"$".$v['price']:'';
                $data['merchantNetPrice'] = !empty($v['merchantNetPrice'])?"$".$v['merchantNetPrice']:'';
                $data['isquestion'] = $v['isquestion']==1?"不存在":"存在问题";
                if($v['confirm_type']==1){
                    $confirm_type = "立即出票";
                }elseif($v['confirm_type']==2){
                    $confirm_type = "确认后出票";
                }else{
                    $confirm_type = "不可用二次确认";
                }
                $data['confirm_type'] = $confirm_type;
                $data['starttime'] = date("Y-m-d",$v['starttime']);
                $data['endtime'] = date("Y-m-d",$v['endtime']);
                $dataArr[] = $data;
            }
            $table_head = array("商品编号","code","商品名称","商品类型","订单类型","城市","售卖价（参考）","采购价（参考）","预约问题","预约类型","开始时间","结束时间");
            $ExportExcel->exportExcel($dataArr, $table_head, "Viator商品列表");
        }else{
            return $this->fetch();
        }
    }

    //商品推荐
    public function recommend(){
        $post=  request()->post();
        if (!empty($post)){
            $t='';
            if (isset($post['popular'])){
                $t= db('goods')->where('goods_id',$post['id'])->update([
                    'popular'=>$post['popular']
                ]);
            }

            if (isset($post['recommend'])) {
                $t = db('goods')->where('goods_id', $post['id'])->update([
                    'recommend' => $post['recommend'],
                ]);
            }

            $res=[];
            if ($t==true){
                $res['msg']='操作成功';
                $res['code']=2;
                $res['db']=Db::getLastsql();
                return $res;
            }else{
                $res['msg']='操作失败';
                $res['code']=1;
                $res['db']=Db::getLastsql();
                return $res;
            }
        }
    }

    //添加商品
    public function addgoods(){
        $g=new G();
        //获取管理员id
        $adminid = Cookie::get('admin');
        if (request()->isPost()){
            $id = $this->request->has('goods_id') ? $this->request->param('goods_id', 0, 'intval') : 0;
            $date = request()->post();
            $gd=new Gdimg();
            if($id>0){//修改
                unset($date['goods_id']);
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['goods_name', 'require', '商品不能为空'],
                    ['goods_tcode', 'require', '产品编号不能为空'],
//                    ['starttime', 'require', '开始时间不能为空'],
//                    ['endtime', 'require', '结束不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($date)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //检查code是否重复
                $goods_tcode = !empty($date['goods_tcode'])?trim($date['goods_tcode']):"";
                if(empty($goods_tcode)) return $this->error('产品编码不能为空');
                $exist_code = db('goods')->where(['goods_tcode'=>$goods_tcode,'goods_id'=>['neq',$id]])->find();
                if(!empty($exist_code)) return $this->error('产品编码重复');
                $date['goods_tcode']=$goods_tcode;
                $info = db("goods")->field('starttime,endtime,goods_status')->find($id);
                $date['starttime'] = empty($date['starttime'])?$info['starttime']:strtotime($date['starttime']);
                $date['endtime'] = empty($date['endtime'])?$info['endtime']:strtotime($date['endtime']);
                //是否更新售卖时间 关联是否更新套餐提示 bywtt
                if($date['starttime']!=$info['starttime'] || $date['endtime']!=$info['endtime']){
                    $date['update_selltime'] = '1';
                }
                $date['updatetime']=time();
                $date['admin_id']=$adminid;
                $date['small_image']='';
                if (!empty($date['goods_image'])){
                    $image=!empty($date['goods_image'])?explode(',',$date['goods_image']):'';
                    $image= array_filter($image);
                    if (!empty($image)){
                        $date['small_image'] = implode(',',$image);
//                        foreach ($image as $u){
//                            $name=md5($u);
//                            $url= $gd->compressImg($name,$u);
//                            $newSrc = (new OssController())->sendLocalImgToOSS($url);
//                            $date['small_image'].=$newSrc.',';
//                        }
                    }
                }

                $goodsname=$g->where("goods_name",$date['goods_name'])->where('goods_id','neq',$id)->find();
                if($goodsname){
                    return $this->error('添加失败：商品名称已存在');
                }
                if( $date['starttime']>$date['endtime']){
                    return $this->error('添加失败：开始时间不能大于结束时间');
                }

                //附属城市判断
                if(isset($date['belong_city']) && !empty($date['belong_city'])){
                    if($date['belong_city']!=999999){
                        $belong_city = explode(",",$date['belong_city']);
                        //将主要城市添加到附属城市中
                        if(!in_array($date['city_id'],$belong_city)){
                            array_unshift($belong_city,$date['city_id']);
                            $date['belong_city'] = implode(",",$belong_city);
                        }
                    }
                }else{
                    $date['belong_city'] = $date['city_id'];
                }

                $date['standard_pro'] = empty($date['standard_pro'])?0:$date['standard_pro'];
                Db::startTrans(); //启动事务
                try {

                    $g->allowField(true)->save($date, ['goods_id' => $id]);
                    //修改上下架通知群消息
                    if(!empty($date['goods_status']) && $date['goods_status']!=$info['goods_status']){
                        $this->checkGoodsStatusToKbx(['goods_id'=>$id,'goods_status'=>$date['goods_status']??'']);
                    }
                    //查询是否存在关联的标品
                    $StandardtagsModel = new StandardtagsModel();

                    $startCity = $date['city_id']??0;
                    $standardData = [];
                    $goodsInfo = db("goods")->where("goods_id",$id)->field("goods_status,goods_name,goods_tcode,orderType")->find();
                    if(!empty($goodsInfo['orderType']) && $goodsInfo['orderType']=='Vehicle'){
                        $standardData['type'] = 1;//行程标品
                    }else{
                        $standardData['type'] = 2;//资源标品
                    }
                    //依据tripid查询标品
                    $productInfo = db('product')->where('item_num',$goodsInfo['goods_tcode'])->find();
                    if(!empty($productInfo)){
                        $standardtrip = db("standardtrip")->where("trip_id",$productInfo['id'])->find();
                        if(!empty($standardtrip)){
                            $standard = db("standard")->where("id",$standardtrip['sid'])->find();
                        }
                    }
                    $standardgoods = db("standard")->where("goods_id",$id)->find();

                    if(empty($standard) && empty($standardgoods)){
                        //新增前检查是否存在相同商品的标品
                        $standardData['goods_id'] = $id;
                        $standardData['name'] = $goodsInfo['goods_name'];
                        $standardData['startCity'] = $startCity;
                        if(isset($date['show_toB'])) $standardData['show_toB'] =$date['show_toB'];
                        $standardData['creattime'] = time();
                        db("standard")->insert($standardData);
                        $standardId = db("standard")->getLastInsID();
                    }elseif(!empty($standard) || !empty($standardgoods)){
                        $standard = !empty($standard)?$standard:$standardgoods;
                        //同步商品信息到标品
                        $standardId = $standard['id'];
                        $standardData['name'] = $date['goods_name'];
                        //$standardData['topCate'] = $date['topCate'];
                        $standardData['startCity'] = $startCity;
                        if(isset($date['show_toB'])) $standardData['show_toB'] = $date['show_toB'];
                        db("standard")->where('id',$standardId)->update($standardData);
                    }
                    trace('标品关联行程信息：'.!empty($standardtrip));
                    if(empty($standardtrip) && !empty($productInfo)){
                        //关联产品
                        $this->linkStandardByGoodsTcode($goodsInfo['goods_tcode'],$standardId);
                    }
                    //当订单类型为包车时，清掉所有类型
                    if(!empty($goodsInfo['orderType']) && $goodsInfo['orderType']=='Vehicle'){
                        $subCates = !empty($date['subCates'])?array_values(array_filter(explode(',',$date['subCates']))):[];
                        if(!empty($subCates)){
                            $StandardtagsModel->where("sid",$standardId)->delete();
                            foreach ($subCates as $key=>$value){
                                $insertData[] = [
                                    'sid'=>$standardId,
                                    'tagid'=>$value,
                                    'sort'=>$key,
                                    'creattime'=>time()
                                ];
                            }
                            $StandardtagsModel->allowField(true)->insertAll($insertData);
                        }
                    }
                    //关联产品的商品无 show_toB 字段
                    if(isset($date['show_toB'])){
                        //B端上架推送到ES
                        $this->pushStandardInfoToESbyUpdateGoods($standardId,$date['show_toB']);
                    }


                    Db::commit(); //提交事务
                    return $this->success('修改成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('修改失败');
                }
            }else{//新增
                unset($date['id']);
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['goods_name', 'require', '商品不能为空'],
                    ['starttime', 'require', '开始时间不能为空'],
                    ['endtime', 'require', '结束不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($date)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //检查code是否重复
                $goods_tcode = !empty($date['goods_tcode'])?trim($date['goods_tcode']):"";
                if(empty($goods_tcode)) return $this->error('产品编码不能为空');
                $exist_code = db('goods')->where(['goods_tcode'=>$goods_tcode,'goods_id'=>['neq',$id]])->find();
                if(!empty($exist_code)) return $this->error('产品编码重复');
                $date['goods_tcode']=$goods_tcode;
                $date['goods_source']=1;
                $date['starttime']=strtotime($date['starttime']);
                $date['endtime']=strtotime($date['endtime']);
                $date['update_selltime']='1';
                $date['creattime']=time();
                $date['updatetime']=time();
                $date['admin_id']=$adminid;
                $date['small_image']='';
                if (!empty($date['goods_image'])){
                    $image=!empty($date['goods_image'])?explode(',',$date['goods_image']):'';
                    $image= array_filter($image);
                    if (!empty($image)){
                        $date['small_image'] = implode(',',$image);
//                        foreach ($image as $u){
//                            $name=md5($u);
//                            $url= $gd->compressImg($name,$u);
//                            $newSrc = (new OssController())->sendLocalImgToOSS($url);
//                            $date['small_image'].=$newSrc.',';
//                        }
                    }
                }

                $goodsname=$g->where("goods_name",$date['goods_name'])->find();
                if($goodsname){
                    return $this->error('添加失败：商品名称已存在');
                }
                if( $date['starttime']>$date['endtime']){
                    return $this->error('添加失败：开始时间不能大于结束时间');
                }
                
                //附属城市判断
                if(isset($date['belong_city']) && !empty($date['belong_city'])){
                    if($date['belong_city']!=999999){
                        $belong_city = explode(",",$date['belong_city']);
                        //将主要城市添加到附属城市中
                        if(!in_array($date['city_id'],$belong_city)){
                            array_unshift($belong_city,$date['city_id']);
                            $date['belong_city'] = implode(",",$belong_city);
                        }
                    }
                }else{
                    $date['belong_city'] = $date['city_id'];
                }

                //判断是否为fareharbor商品
                if(!empty($date['source_id'])){
                    if($date['channel_source']=='fareharbor'){
                        $date['update_selltime']='0';
                        //查看是否存在图片
                        $faregoodsinfo = db("fareharbor_goods")->find($date['source_id']);

                        $date['price_section'] = (new FApi())->getItemSellPrice($faregoodsinfo['usd_price_section']);

                        if(!empty($faregoodsinfo['image_cdn_url']) || !empty($faregoodsinfo['images'])){
                            $images_arr = !empty($faregoodsinfo['image_cdn_url'])?explode(',',$faregoodsinfo['image_cdn_url']):[];
                            $images_arr = array_values(array_filter($images_arr));
                            $images = !empty($faregoodsinfo['images'])?json_decode($faregoodsinfo['images'],true):[];
                            foreach ($images as $kk=>$vv){
                                $images_arr[] = $vv['image_cdn_url'];
                            }
                            $goods_images = array_values(array_filter(explode(",",$date['goods_image'])));
                            if(!empty($images_arr) || !empty($goods_images)){
                                $images_arr = array_merge($images_arr,$goods_images);
                                $date['goods_image'] = implode(",",$images_arr);
                            }
                        }
                    }elseif($date['channel_source']=='hotel'){
                        //等待加入其他类型数据
                        $date['update_selltime']='0';
                        //查看是否存在图片
                        $details = (new HotelSpu())->find($date['source_id']);

                        $date['price_section'] = $details['market_price'];

                        if(!empty($details['thumb'])){
                            $images_arr = !empty($details['thumb'])?explode(',',$details['thumb']):[];
                            $images_arr = array_values(array_filter($images_arr));
                            $goods_images = array_values(array_filter(explode(",",$date['goods_image'])));
                            if(!empty($images_arr) || !empty($goods_images)){
                                $images_arr = array_merge($images_arr,$goods_images);
                                $date['goods_image'] = implode(",",$images_arr);
                            }
                        }
                    }
                }

                $date['standard_pro'] = empty($date['standard_pro'])?0:$date['standard_pro'];
                Db::startTrans(); //启动事务
                try {
                    $g->allowField(true)->save($date);
                    $goods_id = $g->getLastInsID();
                    $this->checkGoodsStatusToKbx(['goods_id'=>$goods_id,'goods_status'=>$date['goods_status']??'']);

                    $show_toB = $date['show_toB']??0;
                    //生成关联标品
                    $standardData = [];
                    $standardType = 2;
                    if(!empty($date['orderType']) && $date['orderType']=='Vehicle'){
                        $standardType = 1;
                    }
                    $standardData['type'] = $standardType;//商品标品
                    $standardData['goods_id'] = $goods_id;
                    $standardData['name'] = $date['goods_name'];
                    $standardData['show_toB'] = $show_toB;
                    $standardData['startCity'] = $date['city_id'];
                    //$standardData['topCate'] = $date['topCate'];
                    $standardData['creattime'] = time();
                    db("standard")->insert($standardData);
                    $standardId = db("standard")->getLastInsID();
                    $standardTrip = db('standardtrip')->where('sid',$standardId)->find();
                    if(empty($standardTrip) && !empty($date['goods_tcode'])){
                        //关联产品
                        $this->linkStandardByGoodsTcode($date['goods_tcode'],$standardId);
                    }

                    $StandardtagsModel = new StandardtagsModel();
                    //保存toB分类
                    $StandardtagsModel->where("sid",$standardId)->delete();
                    if($date['orderType']!='Vehicle'){
                        $subCates = !empty($date['subCates'])?array_values(array_filter(explode(',',$date['subCates']))):[];
                        $StandardtagsModel->where("sid",$standardId)->delete();
                        if(!empty($subCates)){
                            foreach ($subCates as $key=>$value){
                                $insertData[] = [
                                    'sid'=>$standardId,
                                    'tagid'=>$value,
                                    'sort'=>$key,
                                    'creattime'=>time()
                                ];
                            }
                            $StandardtagsModel->allowField(true)->insertAll($insertData);
                        }
                    }
                    //B端上架推送到ES
                    if(isset($date['show_toB'])){
                        $this->pushStandardInfoToESbyUpdateGoods($standardId,$date['show_toB']);
                    }

                    Db::commit(); //提交事务
                    return $this->success('添加成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('添加失败');
                }
            }
        }else{
            //修改
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $goods=$g->where("goods_id",$id)->find();
            //获取tag
            $tag=$goods['tag_id'];
            $tag=explode(',',$tag);
            if($tag[0]){
                $tagdata=Array();
                foreach($tag as $key=>$value){
                    $tags=Db::name('tag')->where("tag_id",$value)->field("tag_name,tag_id")->find();
                    $tagdata[$key]=$tags;
                }

            }else{
                $tagdata='';
            }
            $this->assign('tagdata',$tagdata);

            //获取关联项目
            $relation=$goods['relation_type'];
            $goodscity=$goods['city_id'];
            $belong_city=$goods['belong_city'];
            $goodslocation=$goods['goods_location'];
            $goodsclassify=$goods['classify_id'];

            if ($relation=='1'){
                $da = $g->product($goodscity);
            }else if ($relation=='2'){
                $da = $g->poi($goodscity,$goodsclassify);
            }else{
                $da='';
            }
            //获取轮播图
            $goodsimage=$goods['goods_image'];
            $goodsimage=explode(',',$goodsimage);
            $this->assign('goodsimage',$goodsimage);
            $this->assign('goods',$goods);
            $this->assign('relation',$da);

            //查询商品关联的标品
            $standard = db("standard")->where("goods_id",$id)->find();
            if(!empty($standard)){
                //正在使用的关联标签
                $tagsData = db("standardtags")
                    ->alias("s")
                    ->join("tag t","s.tagid=t.tag_id","left")
                    ->where(['t.tag_status'=>1,'t.tob_show'=>1,"s.sid"=>$standard['id']])
                    ->order("s.sort asc,s.id asc")
                    ->select();
                $this->assign('tagsData', $tagsData);
            }

            $this->assign('standard',$standard);

            //关联产品的商品不可编辑
            if(!empty($goods['goods_tcode'])){
                $exist_pro = db('product')->where('item_num',$goods['goods_tcode'])->find();
            }
        }
        $exist_pro = !empty($exist_pro)?1:0;
        $this->assign('exist_pro', $exist_pro);

        $city=$g->city();

        if($goodscity){
            $team=$g->team($goodscity,0);
        }else if ($city[0]['id']){
            $team=$g->team($city[0]['id'],0);
        }else{
            $team=[];
        }
        //附属城市
        $belongCityList = [];
        if(isset($belong_city) && !empty($belong_city)){
            if($belong_city!=999999){
                $belong_city = array_filter(explode(",",$belong_city));
                foreach ($city as $key => $value) {
                    if(in_array($value['id'],$belong_city)){
                        $belongCityList[] = $value;
                    }
                }
                $belong_city = implode(",",$belong_city);
            }
        }else{
            $belong_city = "";
        }

        $this->assign("belongcityid",$belong_city);
        $this->assign("belongCityList",$belongCityList);

        //关联项目
        $projectList = [];
        if(isset($goodslocation) && !empty($goodslocation)){
            $goodslocation = array_filter(explode(",",$goodslocation));
            foreach ($team as $key => $value) {
                if(in_array($value['id'],$goodslocation)){
                    $projectList[] = $value;
                }
            }
            $goodslocation = implode(",",$goodslocation);

        }else{
            $goodslocation = "";
        }
        $this->assign("goodslocation",$goodslocation);
        $this->assign("projectList",$projectList);

        //供应商
        list($supplier,$supplierNameArr) = (new Product())->getSupplierList();

        $this->assign('supplier',$supplier);


        //商品的订单类型
//        $orderType = array(
//            array('type'=>'Ticket_FIT','name'=>'地接社标品','orderFlag'=>0),
//            array('type'=>'Ticket_POI','name'=>'门票类产品','orderFlag'=>0),
//            array('type'=>'Hotel','name'=>'酒店','orderFlag'=>0),
//            array('type'=>'Custom','name'=>'定制产品','orderFlag'=>1),
//            array('type'=>'Vehicle','name'=>'用车','orderFlag'=>1),
//            array('type'=>'Ticket_AIR','name'=>'机票','orderFlag'=>0),
//            array('type'=>'Rental_Device','name'=>'物品购买/租赁','orderFlag'=>1),
//            array('type'=>'Other','name'=>'其它','orderFlag'=>1),
//            array('type'=>'Price_Gap','name'=>'补差价','orderFlag'=>1),
//            array('type'=>'Self_Drive','name'=>'自驾游','orderFlag'=>1),
//            array('type'=>'Personal_Tailor','name'=>'私人定制服务','orderFlag'=>1),
//            array('type'=>'Subscription','name'=>'代订服务','orderFlag'=>1),
//        );
        $orderType = db('service_type')->select();
        $this->assign('orderType',$orderType);


        //新增商品的标签
        $goodstags=Db::name('goodstag')->where(['tag_status'=>1])->field('tag_id,tag_name')->select();
        $companyList = (new F())->getFareharborData();
        $itemList = db("fareharbor_goods")->field("fare_goods_id,item_id,item_name,company")->order("fare_goods_id asc")->select();
        $this->assign('companyList',$companyList);
        $this->assign('itemList',$itemList);
        $item = [];
        if($goods['channel_source']=='fareharbor'){
            foreach ($itemList as $k=>$v){
                if($v['fare_goods_id']==$goods['source_id']){
                    $item = $v;
                    break;
                }
            }
        }

        $companyList = (new F())->getFareharborData();
        $itemList = db('fareharbor_goods')->where("status",'1')->select();
        $this->assign('companyList',$companyList);
        $this->assign('itemList',$itemList);
        $this->assign('item',$item);
        $this->assign('trip',$g->trip());
        $this->assign('tag',$g->tag());
        $this->assign('city',$city);
        $this->assign('team',$team);
        $this->assign('classify',$g->classify());
        $this->assign('thumb','');
        $this->assign('fileid',"");
        $this->assign('goodstags',$goodstags);


        //********************************* toB分类 *********************************
        //顶级分类
        //获取tob标签的类别
        $topCates = (new SDModel())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCates,'tagTypeIds'));
        $tags = db("tag")
            ->where(['tag_status'=>1])//未删除
            ->where(['tob_show'=>1])//tob 展示
            ->where(['tag_type'=>['in',$tagTypeIds]])
            ->order("tag_id asc")
            ->select();
//        foreach ($topCates as $key=>$value){
//            $topCates[$key]['subCates'] = [];
//            $tag_types = explode(',',$value['tagTypeIds']);
//            foreach ($tags as $tag_key=>$tag_value){
//                if(in_array($tag_value['tag_type'],$tag_types)){
//                    $topCates[$key]['subCates'][] = $tag_value;
//                    unset($tags[$tag_key]);
//                }
//            }
//        }
        $this->assign("tags",$tags);
        $hotelList = (new HotelSpu())->getAdminHotelList([],999);
        $this->assign("hotelList",$hotelList);

        return $this->fetch();
    }

    //添加第三方商品
    public function addgoodsother(){
        $g=new G();
        //获取管理员id
        $adminid = Cookie::get('admin');
        if (request()->isPost()){
            $id = $this->request->has('goods_id') ? $this->request->param('goods_id', 0, 'intval') : 0;
            if($id>0){
                //修改
                $date=request()->post();
                $goods_id=$date['goods_id'];
                unset($date['goods_id']);
                $date['updating']=time();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['goods_name', 'require', '商品不能为空'],
                    ['starttime', 'require', '开始时间不能为空'],
                    ['endtime', 'require', '结束不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($date)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $date['starttime']=strtotime($date['starttime']);
                $date['endtime']=strtotime($date['endtime']);
                $date['updatetime']=time();
                $date['admin_id']=$adminid;

                $goodsname=$g->where("goods_name",$date['goods_name'])->where('goods_id','neq',$id)->find();
                if($goodsname){
                    return $this->error('添加失败：商品名称已存在');
                }
                if( $date['starttime']>$date['endtime']){
                    return $this->error('添加失败：开始时间不能大于结束时间');
                }
                //如果是上架  则获取商品价格
                $old_status=Db::name('goods')->where('goods_id',$goods_id)->field('goods_status')->find()['goods_status'];
                if($date['goods_status']==1 && $old_status!=1){
                    $res=$this->addprice($goods_id);
                    if($res['code']!='003'){
                        return $this->error($res['msg']);
                    }
                }
                Db::startTrans(); //启动事务
                try {
                    $g->allowField(true)->save($date, ['goods_id' => $id]);

                    $goodsInfo = db("goods")->where("goods_id",$id)->field("goods_status,goods_name,goods_tcode,orderType")->find();
                    //查询是否存在关联的标品
                    $standard = db("standard")->where("goods_id",$id)->find();
                    $StandardtagsModel = new StandardtagsModel();
                    $standardData = [];
                    $standardData['type'] = 2;//资源标品
                    if(!empty($goodsInfo['orderType']) && $goodsInfo['orderType']=='Vehicle'){
                        $standardData['type'] = 1;//行程标品
                    }
                    if(empty($standard)){
                        $standardData['goods_id'] = $id;
                        $standardData['name'] = $goodsInfo['goods_name'];
                        $standardData['show_toB'] = $date['show_toB']??0;
                        $standardData['startCity'] = $date['city_id']??0;
                        //$standardData['topCate'] = $date['topCate']??0;
                        $standardData['creattime'] = time();
                        db("standard")->insert($standardData);
                        $standardId = db("standard")->getLastInsID();

                    }else{
                        $standardId = $standard['id'];
                        $standardData['name'] = $goodsInfo['goods_name'];
                        $standardData['show_toB'] = $date['show_toB']??0;
                        $standardData['startCity'] = $date['city_id']??0;
                        //$standardData['topCate'] = $date['topCate']??0;
                        db("standard")->where('id',$standardId)->update($standardData);
                    }
                    $standardTrip = db('standardtrip')->where('sid',$standardId)->find();
                    if(empty($standardTrip) && !empty($goodsInfo['goods_tcode'])){
                        //关联产品
                        $this->linkStandardByGoodsTcode($goodsInfo['goods_tcode'],$standardId);
                    }

                    //保存toB分类
                    //当订单类型为包车时，清掉所有类型
                    if($date['orderType']!='Vehicle'){
                        $subCates = !empty($date['subCates'])?array_values(array_filter(explode(',',$date['subCates']))):[];
                        $StandardtagsModel->where("sid",$standardId)->delete();
                        if(!empty($subCates)){
                            foreach ($subCates as $key=>$value){
                                $insertData[] = [
                                    'sid'=>$standardId,
                                    'tagid'=>$value,
                                    'sort'=>$key,
                                    'creattime'=>time()
                                ];
                            }
                            $StandardtagsModel->allowField(true)->insertAll($insertData);
                        }
                    }
                    //B端上架推送到ES
                    $this->pushStandardInfoToESbyUpdateGoods($standardId,$date['show_toB']??0);
                    Db::commit(); //提交事务
                    return $this->success('修改成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('修改失败');
                }
            }else{
                //新增
                $date=request()->post();
                unset($date['id']);
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['goods_name', 'require', '商品不能为空'],
                    ['starttime', 'require', '开始时间不能为空'],
                    ['endtime', 'require', '结束不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($date)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $date['goods_source']=1;
                $date['starttime']=strtotime($date['starttime']);
                $date['endtime']=strtotime($date['endtime']);
                $date['creattime']=time();
                $date['updatetime']=time();
                $date['admin_id']=$adminid;

                $goodsname=$g->where("goods_name",$date['goods_name'])->find();
                if($goodsname){
                    return $this->error('添加失败：商品名称已存在');
                }
                if( $date['starttime']>$date['endtime']){
                    return $this->error('添加失败：开始时间不能大于结束时间');
                }
                Db::startTrans(); //启动事务
                try {
                    $g->allowField(true)->save($date);
                    $goods_id = $g->getLastInsID();

                    //生成关联标品
                    $goodsInfo = db("goods")->where("goods_id",$id)->field("goods_status,goods_name,orderType")->find();
                    $standardData = [];
                    $standardData['type'] = 2;
                    if(!empty($date['orderType']) && $date['orderType']=='Vehicle'){
                        $standardData['type'] = 1;
                    }
                    $standardData['goods_id'] = $goods_id;
                    $standardData['name'] = $goodsInfo['goods_name'];
                    $standardData['show_toB'] = $date['show_toB']??0;
                    $standardData['startCity'] = $date['city_id']??0;
                    //$standardData['topCate'] = $date['topCate']??0;
                    $standardData['creattime'] = time();
                    db("standard")->insert($standardData);
                    $standardId = db("standard")->getLastInsID();
                    $standardTrip = db('standardtrip')->where('sid',$standardId)->find();
                    if(empty($standardTrip) && !empty($date['goods_tcode'])){
                        //关联产品
                        $this->linkStandardByGoodsTcode($date['goods_tcode'],$standardId);
                    }

                    $StandardtagsModel = new StandardtagsModel();
                    //保存toB分类
                    $StandardtagsModel->where("sid",$standardId)->delete();
                    if($date['orderType']!='Vehicle'){
                        $subCates = !empty($date['subCates'])?array_values(array_filter(explode(',',$date['subCates']))):[];
                        $StandardtagsModel->where("sid",$standardId)->delete();
                        if(!empty($subCates)){
                            foreach ($subCates as $key=>$value){
                                $insertData[] = [
                                    'sid'=>$standardId,
                                    'tagid'=>$value,
                                    'sort'=>$key,
                                    'creattime'=>time()
                                ];
                            }
                            $StandardtagsModel->allowField(true)->insertAll($insertData);
                        }
                    }

                    //B端上架推送到ES
                    $this->pushStandardInfoToESbyUpdateGoods($standardId,$date['show_toB']??0);
                    Db::commit(); //提交事务
                    return $this->success('添加成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('添加失败');
                }
            }
        }else{//修改
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $goods=$g->where("goods_id",$id)->find();
            //获取tag
            $tag=$goods['tag_id'];
            $tag=explode(',',$tag);
            if($tag[0]){
                $tagdata=Array();
                foreach($tag as $key=>$value){
                    $tags=Db::name('tag')->where("tag_id",$value)->field("tag_name,tag_id")->find();
                    $tagdata[$key]=$tags;
                }

            }else{
                $tagdata='';
            }
            $this->assign('tagdata',$tagdata);

            //获取关联项目
            $relation=$goods['relation_type'];
            $goodscity=$goods['city_id'];
            $goodsclassify=$goods['classify_id'];


            if ($relation=='1'){
                $da=  $g->trip($goodscity);
            }else if ($relation=='2'){
                $da=  $g->poi($goodscity,$goodsclassify);
            }else{
                $da='';
            }
            //获取轮播图
            $goodsimage=$goods['goods_image'];
            $goodsimage=explode(',',$goodsimage);
            $this->assign('goodsimage',$goodsimage);
            $this->assign('goods',$goods);
            $this->assign('relation',$da);

            //查询商品关联的标品
            $standard = db("standard")->where("goods_id",$id)->find();
            if(!empty($standard)){
                //正在使用的关联标签
                $tagsData = db("standardtags")
                    ->alias("s")
                    ->join("tag t","s.tagid=t.tag_id","left")
                    ->where(['t.tag_status'=>1,'t.tob_show'=>1,"s.sid"=>$standard['id']])
                    ->order("s.sort asc,s.id asc")
                    ->select();
                $this->assign('tagsData',$tagsData);
            }

            $this->assign('standard',$standard);
        }
        $city=$g->city();

        if($goodscity){
            $team=$g->team($goodscity);
        }else if ($city[0]['id']){
            $team=$g->team($city[0]['id']);
        }else{
            $team='';
        }

        //商品的订单类型
        $orderType = db('service_type')->select();
        $this->assign('orderType',$orderType);

        //新增商品的标签
        $goodstags=Db::name('goodstag')->where(['tag_status'=>1])->field('tag_id,tag_name')->select();

        $this->assign('trip',$g->trip());
        $this->assign('tag',$g->tag());
        $this->assign('city',$city);
        $this->assign('team',$team);
        $this->assign('classify',$g->classify());
        $this->assign('thumb','');
        $this->assign('fileid',"");
        $this->assign('goodstags',$goodstags);

        //********************************* toB分类 *********************************
        //获取tob标签的类别
        $topCates = (new SDModel())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCates,'tagTypeIds'));
        $tags = db("tag")
            ->where(['tag_status'=>1])//未删除
            ->where(['tob_show'=>1])//tob 展示
            ->where(['tag_type'=>['in',$tagTypeIds]])
            ->order("tag_id asc")
            ->select();
//        foreach ($topCates as $key=>$value){
//            $topCates[$key]['subCates'] = [];
//            $tag_types = explode(',',$value['tagTypeIds']);
//            foreach ($tags as $tag_key=>$tag_value){
//                if(in_array($tag_value['tag_type'],$tag_types)){
//                    $topCates[$key]['subCates'][] = $tag_value;
//                    unset($tags[$tag_key]);
//                }
//            }
//        }
        $this->assign("tags",$tags);

        return $this->fetch();
    }

    //更新第三方数据
    public function changDetailT(){
        if($this->request->isPost()){
            $data=$this->request->request();
            $data['isupdated']=0;
            $code=$data['code'];

            unset($data['code']);
            unset($data['s']);
            //修改主表
            Db::name('goods')->where('code',$code)->update($data);
            $res=Db::name('goods_backups')->where('code',$code)->find();
            if(empty($res)){
                $res=[
                    'code'=>1,
                    'msg'=>'没有该数据的最新数据'
                ];
                return $res;
            }
            unset($res['id']);
            unset($res['updatetime']);
            unset($res['updating']);

            Db::name('goods_backupsmd5')->where('code',$code)->update($res);
            $res=[
                'code'=>1,
                'msg'=>'更新完毕'
            ];
            return $res;
        }else{
            $re_title=[
                'goods_name'=>'商品名称',
                'goods_englishname'=>'商品英文名称',
                'price'=>'价格(美元)',
                'merchantNetPrice'=>'采购价格(美元)',
                'goods_usetime'=>'用时参考',
                'price_include'=>'费用包含',
                'price_noinclude'=>'费用不含',
                'goods_careful'=>'注意事项',
                'goods_retreating'=>'退改规则',
                'goods_introduce'=>'简介',
            ];
            $code = $this->request->param('code');
            $data=Db::name('goods_backups')->where('code',$code)->find();

            //获取现有对比数据
            $data1=Db::name('goods_backupsmd5')->where('code',$code)->find();
            //获取对比字段
            $resList=$this->searchGoods($data,$data1);

            //获取现在显示字段
            $data2=Db::name('goods')->where('code',$code)->find();

            $result=[];
            foreach ($resList as $a){
                if($a=='allTravellerNamesRequired'){
                    $b='alltravellermessage';
                }else{
                    $b=$a;
                }
                $result[$a]=[
                    'title'=>empty($re_title[$a])?$a:$re_title[$a],
                    'newmsg'=>$data[$a],
                    'oldmsg'=>$data1[$a],
                    'msg'=>$data2[$b],
                    'key'=>$a,
                ];
            }
            $this->assign('code',$code);
            $this->assign('data',$result);
            return $this->fetch();
        }

    }

    /*
     * 更新：相似度判断
     */
    public function searchGoods($data,$res){
        unset($data['goods_image']); //图片不做对比
        unset($data['updatetime']); //时间不做对比
        unset($data['updating']); //时间不做对比
        unset($data['id']); //时间不做对比
        $delstr=['allTravellerNamesRequired','isquestion','bookingEngine','goods_enintroduce'];//不在显示的字段 自主更新
        $list=[];
        $listall=[];
        if(!empty($data)){
            foreach ($data as $v=>$k){
                $md1=md5($k);
                $md2=md5($res[$v]);
                $listall[]=$v;
                if($md1==$md2){
                    continue;
                }
                $list[]=$v;
            }
        }

        if(empty($list)){
            return $listall;
        }else{
            return $list;
        }
    }

    //商品规格
    public function addclassify(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $table_name = ['出行类型','默认价格','数量','最低下单数','最小增长数'];
        //是新增操作
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post()['data'];
            Db::startTrans(); //启动事务
            try {
                //循环规格参数，提交
                $goodsdata['goods_id']=$id;
                $goodsdata['specs_status']=1;
                $changestatus['specs_status']=2;

                Db::name('specs')->where("goods_id",$id)->where("specs_types",1)->update($changestatus);

                foreach ($post as $key=>$value){
                    $changepersonstatus['person_status']=2;
                    $goodsdata['specs_name']=$value['specs_name'];
                    if(!empty($value['specs_id'])){
                        Db::name('person')->where("specs_id",$value['specs_id'])->update($changepersonstatus);
                        $goodsdata['updatetime']=time();

                        Db::name('specs')->where("specs_id",$value['specs_id'])->update($goodsdata);
                        $pid= Db::name('specs')->where("pid",$value['specs_id'])->find();
                        if ($pid==true){
                            Db::name('specs')->where("pid",$value['specs_id'])->where('specs_status',1)->update([
                                'specs_name' => $value['specs_name'],
                            ]);
                        }

                        $specsdata['specs_id']=$value['specs_id'];
                        $specsdata['person_status']=1;
                        $specsdata['updatetime']=time();

                        if(!empty($value['persondata'])){
                            foreach ($value['persondata'] as $k=>$v){
                                $specsdata['person_name']=$v['person_name'];
                                $specsdata['person_price']=$v['person_price'];
                                $specsdata['person_num']=$v['person_num'];
                                $specsdata['minorder_num']=$v['minorder_num'];
                                $specsdata['inc_order_num']=$v['inc_order_num'];
                                if(!empty($v['person_id'])){
                                    Db::name('person')->where("person_id",$v['person_id'])->update($specsdata);
                                    $pid= Db::name('person')->where("pid",$v['person_id'])->find();
                                    if ($pid==true){
                                        Db::name('person')->where("pid",$v['person_id'])->update([
                                            'person_name' => $v['person_name'],
                                        ]);
                                    }
                                    //修改相关的person信息
                                    unset($specsdata['person_price']);
                                    db('personday')->where('person_id',$v['person_id'])->update([
                                        'person_name'=>$v['person_name'],
                                        'person_num'=>$v['person_num'],
                                        'minorder_num'=>$v['minorder_num'],
                                        'inc_order_num'=>$v['inc_order_num'],
                                    ]);
                                }else{
                                    $specsdata['creattime']=time();
                                    Db::name('person')->insert($specsdata);
                                }
                            }
                        }
                    }else{
                        $goodsdata['creattime']=time();
                        $goodsdata['updatetime']=time();
                        Db::name('specs')->insert($goodsdata);
                        $specsid=Db::name('specs')->getLastInsID();//规格id
                        $specsdata['specs_id']=$specsid;
                        $specsdata['person_status']=1;
                        $specsdata['creattime']=time();
                        $specsdata['updatetime']=time();
                        if(!empty($value['persondata'])){
                            foreach ($value['persondata'] as $k=>$v){
                                $specsdata['person_name']=$v['person_name'];
                                $specsdata['person_price']=$v['person_price'];
                                $specsdata['person_num']=$v['person_num'];
                                $specsdata['minorder_num']=$v['minorder_num'];
                                $specsdata['inc_order_num']=$v['inc_order_num'];
                                Db::name('person')->insert($specsdata);
                            }
                        }
                    }
                }
                Db::commit(); //提交事务

                //删除商品下的所有无用套餐数据
                $this->delSpecsAndPerson($id);

                return $this->success('提交商品规格成功', 'admin/member/member');
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error('提交商品规格失败');
            }
        }else{
            $specs=Db::name('specs')->where("goods_id",$id)->where("specs_status",1)->where("specs_types",1)->select();
            if($specs){
                foreach ($specs as $key=>$value){
                    $specs[$key]['person']=Array();
                    $specs_id=$value['specs_id'];

                    $person=Db::name('person')->where("specs_id",$specs_id)->where("person_status",1)->select();

                    array_push($specs[$key]['person'],$person);
                }
                $this->assign('specs',$specs);
            }else{
                $this->assign('specs','');
            }
        }

        $this->assign('id',$id);
        $goods = db("goods")->field("is_group")->find($id);
        if(!empty($goods) && $goods['is_group']==1){
            $table_name = ['拼团类型','价格','拼团人数','最小成拼人数','最小增长数'];
        }
        $this->assign('table_name',$table_name);
        return $this->fetch();
    }

    //切换内容
    public function findpoi(){
        $g=new G();
        if (request()->isAjax()){
            $id=  input('id');
            $city=  input('city');
            $classify=  input('goods_classify');
            $team=$g->team($city);
            if ($id=='1'){
                $da=  $g->trip($city);
            }else if ($id=='2'){
                $da=  $g->poi($city,$classify);
            }else{
                return $this->error('参数错误');
            }
            $data['team']=$team;
            $data['poi']=$da;
            return json_encode($data);
        }
    }

    //下拉
    public function xiala(){
        $g=new G();
        if (request()->isAjax()){
            $sid=  input('sid');
            $id=  input('id');
            if ($sid=='1'){
                $da=  $g->tripsee($id);
            }else if ($sid=='2'){
                $da=  $g->poisee($id);
            }else{
                return $this->error('参数错误');
            }
            return json_encode($da);
        }
    }

    //编辑商品
    public function edit(){
        $g=new G();
        if (request()->isPost()){
            $da=request()->post();
            $ed= $g->edit($da);
            if ($ed==true){
                return $this->success('编辑成功');
            }else{
                return $this->success('编辑失败');
            }

        }
        $this->assign('g',$g);
        $this->assign( 'aa',$g->where('goods_id',input('id'))->find());
        $this->assign('thumb','');
        return $this->fetch();
    }

    //商品上下架
    public function shelves(){
        if (request()->isAjax()){
            $id=request()->request();
            $goods = Db::name("goods")->where("goods_id",$id['id'])->find();
            if($goods['orderType']==null || empty($goods['orderType'])){
                return $this->error('请选择订单类型再上架');
            }
            $id['show'] = $goods['show'];
            $g=new G();
            $date= $g->shelves($id);
            if ($date==true){
                return $this->success('操作成功');
            }else{
                return $this->error('操作失败');
            }
        }
    }

    public function copy(){
        $g=new G();
        if (request()->isPost()){
            $da=request()->post();
            $ed= $g->add($da);
            if ($ed==true){
                return $this->success('复制成功');
            }else{
                return $this->success('复制失败');
            }

        }

        $this->assign( 'aa',$g->where('goods_id',input('id'))->find());
        $this->assign('g',$g);
        $this->assign('trip',$g->trip());
        $this->assign('thumb','');
        return $this->fetch();
    }

    //上架是更新价格规格
    public function addprice($id=''){
        if(empty($id)){
            $id=input('id');
        }
        $code=Db::name('goods')->where('goods_id',$id)->field('code')->find()['code'];

        //查询的月份
        $month=date('m');
        $lastMonth=date('m',strtotime('+1 month'));
        //增至六个月
        $lastMonth_3=date('m',strtotime('+2 month'));
        $lastMonth_4=date('m',strtotime('+3 month'));
        $lastMonth_5=date('m',strtotime('+4 month'));
        $lastMonth_6=date('m',strtotime('+5 month'));


        $viator=new Viator();
        $goodsdetail=$viator->goodsDetail($code);
        if(empty($goodsdetail)){
            //商品下架
            $updateArr['accidentDrop'] = 1;//记录意外下架
            $updateArr['goods_status'] = 2;
            Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);

            //执行标品下架
            $standard = db("standard")->where("goods_id",$id)->field("id")->find();
            if(!empty($standard)){
                db("standard")->where('id',$standard['id'])->update(['show_toB'=>0]);
            }

            //发送邮件给小美
            $goods = Db::name('goods')->where('code',$code)->field("goods_name")->find();
            $title = "【".$goods['goods_name']."】商品被自动下架了，请速查看！";
            $content = "下架商品编号：".$code."。 下架原因：goodsdetail未获取到";
            $msg=new Msg();
            $msg->kbxemailcode($title,$content,'chris@kuaibangxing.com');

            $reselut=[
                'code'=>'001',
                'msg'=>'供应商已下架'
            ];
            return $reselut;
        }

        //获取价格
        $resArray1=$viator->getPriceShow($code,$month,$goodsdetail['ageBands']);
        $resArray2=$viator->getPriceShow($code,$lastMonth,$goodsdetail['ageBands']);
        //获取价格范围增至六个月
        $resArray3=$viator->getPriceShow($code,$lastMonth_3,$goodsdetail['ageBands']);
        $resArray4=$viator->getPriceShow($code,$lastMonth_4,$goodsdetail['ageBands']);
        $resArray5=$viator->getPriceShow($code,$lastMonth_5,$goodsdetail['ageBands']);
        $resArray6=$viator->getPriceShow($code,$lastMonth_6,$goodsdetail['ageBands']);

        if(empty($resArray1)){
            $res_arr = array();
            if(!empty($resArray2)){
                $resArray1=$resArray2;
                $res_arr = array($resArray3,$resArray4,$resArray5,$resArray6);
            }else{
                if(!empty($resArray3)){
                    $resArray1=$resArray3;
                    $res_arr = array($resArray4,$resArray5,$resArray6);
                }else{
                    if(!empty($resArray4)){
                        $resArray1=$resArray4;
                        $res_arr = array($resArray5,$resArray6);
                    }else{
                        if(!empty($resArray5)){
                            $resArray1=$resArray5;
                            $res_arr = array($resArray6);
                        }else{
                            if(!empty($resArray6)){
                                $resArray1=$resArray6;
                            }
                        }
                    }
                }
            }
        }else{
            $res_arr = array($resArray2,$resArray3,$resArray4,$resArray5,$resArray6);
        }

        foreach ($res_arr as $res_v) {
            if(!empty($res_v)){
                foreach ($res_v as $a=>$d){
                    if(!isset($resArray1[$a])){
                        $resArray1[$a]=[];
                    }
                    foreach ($d as $k){
                        array_push($resArray1[$a],$k);
                    }
                }
            }
        }

        if(is_array($resArray1)){
            $resArray1=array_filter($resArray1);
        }

        //获取套餐分类
        $tourGrades=$viator->getGrend($code,$goodsdetail['tourGrades']);

        //补充 如果6个月内没有价格 则商品下架
        if(empty($resArray1)){
            //商品下架
            $updateArr['accidentDrop'] = 1;//记录意外下架
            $updateArr['goods_status'] = 2;
            Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);

            //执行标品下架
            $standard = db("standard")->where("goods_id",$id)->field("id")->find();
            if(!empty($standard)){
                db("standard")->where('id',$standard['id'])->update(['show_toB'=>0]);
            }

            //发送邮件给小美
            $goods = Db::name('goods')->where('code',$code)->field("goods_name")->find();
            $title = "【".$goods['goods_name']."】商品被自动下架了，请速查看！";
            $content = "下架商品编号：".$code."。 下架原因：未来6个月没有可预约的行程安排1";
            $msg=new Msg();
            $msg->kbxemailcode($title,$content,'chris@kuaibangxing.com');

            $reselut=[
                'code'=>'002',
                'msg'=>'未来6个月没有可预约的行程安排1'
            ];
            return $reselut;
        }else{
            $endtime=[];
            foreach ($resArray1 as $a){
                $endtime[]=strtotime($a[0]['bookingDate']);
            }
            $endtime=min($endtime);
            $nexttime=strtotime('+5 month');
            $lasttime=strtotime(date('Y-m-t 23:00:00',$nexttime));
            if($endtime>$lasttime){
                $reselut=[
                    'code'=>'002',
                    'msg'=>'未来6个月没有可预约的行程安排2'
                ];
                return $reselut;
            }
        }

        //将没有价格的分类去掉
        $temp_key=[];
        foreach ($resArray1 as $res_key=>$res_val){
            $temp_key[]=$res_key;
        }
        foreach ($tourGrades as $grade_key=>$grade){
            if(!in_array($grade['gradeCode'],$temp_key)){
                unset($tourGrades[$grade_key]);
            }
        }
        //价格缓存
        cache($code.'price',$resArray1);
        //套餐类型缓存
        cache($code.'type',$tourGrades);

        //数据库写入记录
        $time=date('Y-m-d H:i:s');
        $res=Db::name('goods_price')->where('code',$code)->find();
        if($res){
            Db::name('goods_price')->where('code',$code)->update(['time'=>$time]);
        }else{
            $data=[
                'code'=>$code,
                'time'=>$time
            ];
            Db::name('goods_price')->insert($data);
        }
        $reselut=[
            'code'=>'003',
            'msg'=>'价格和规格获取成功'
        ];
        return $reselut;
    }

    /****
     * 查询价格
     */
    public function showprice () {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $viator=new Viator();
        $data = array();
        if($id>0){
            $codeArr = Db::name('goods')->where('goods_id',$id)->field('code')->find();
            $code = $codeArr['code'];
            $cache = cache($code.'price');
            $type = cache($code.'type');

            if(empty($type)){//不存在缓存套餐时
                if(401==$viator->timePrice($code)){
                    return $this->error('近六个月未获取到价格');
                }
            }

            if(empty($cache)){//不存在缓存价格时
                if(401==$viator->timePrice($code)){
                    return $this->error('近六个月未获取到价格');
                }
            }

            //验证是否抓取6个月
            if(!isset($cache['month_num']) || $cache['month_num']<6){
                if(401==$viator->timePrice($code)){
                    return $this->error('近六个月未获取到价格');
                }
            }

            $type = cache($code.'type');
            $cache = cache($code.'price');

            if(!empty($type)){
                //修改过的自定义套餐名称集
                $where_name['code'] = $code;
                $specsName = Db::name('specsname')->where($where_name)->select();
                $nameArr = array();
                if(!empty($specsName)){
                    foreach ($specsName as $k_name=>$v_name){
                        $nameArr[$v_name['grade_code']] = $v_name['new_name'];
                    }
                }

                $tourGrade = array();
                $num = 1;
                foreach ($type as $k=>$v) {
                    if(isset($nameArr[$v['gradeCode']])){
                        $tourGrade['gradeTitle'] = $nameArr[$v['gradeCode']];//使用修改过的自定义套餐名称
                    }else{
                        $tourGrade['gradeTitle'] = !empty($v['specs_name']) ? $v['specs_name'] : $v['specs_ename'];

                        //为解决Viator商品的套餐名字段更新问题，自动对比增加
                        $new_grade_code_Arr = explode("~",$v['gradeCode']);
                        $new_s = !empty($new_grade_code_Arr[0]) ? $new_grade_code_Arr[0] : '';
                        if($new_s!==''){
                            $new_specs_name = $v['specs_name'];
                            $grade_name = isset($nameArr[$new_s]) ? $nameArr[$new_s] : $new_specs_name;
                            $p_data = array();
                            $p_data['code'] = $v['code'];
                            $p_data['grade_code'] = $v['gradeCode'];
                            $p_data['specs_name'] = $new_specs_name;
                            $p_data['new_name'] = $grade_name;
                            $tourGrade['gradeTitle'] = $grade_name;

                            //防止重复插入
                            $p_specsname = db("specsname")->where([
                                "code"=>$code,
                                "grade_code"=>$v['gradeCode']
                            ])->find();
                            if(empty($p_specsname)){
                                db("specsname")->insert($p_data);
                            }
                        }
                    }

                    $tourGrade['specs_name'] = $v['specs_name'];
                    $tourGrade['specs_ename'] = isset($v['specs_ename'])?$v['specs_ename']:'';
                    $tourGrade['gradeCode'] = $v['gradeCode'];
                    $tourGrade['code'] = $code;
                    $tourGrade['time_id'] = "timeid".$num;

                    $date_arr = array();
                    foreach ($cache[$v['gradeCode']] as $gc_k=>$gc_v) {
                        if(!empty($gc_v['bookingDate']) && $gc_v['bookingDate']!==''){
                            $day = substr($gc_v['bookingDate'],-2);
                        }
                        $date_arr[$gc_v['bookingDate']] = $day;
                    }
                    $tourGrade['date_arr'] = $date_arr;
                    $data[] = $tourGrade;
                    $num++;
                }

                $this->assign('code',$code);
                $this->assign('data',$data);
                return $this->fetch();
            }else{
                return $this->error('获取套餐失败');
            }
        }
    }

    public function getPriceFromDate (){
        if($this->request->isPost()) {
            $post = request()->post();
            $code = $post['code'];
            $gradeCode = $post['gradeCode'];
            $date = $post['date'];
            $cache = cache($code.'price');

            $eto_list=[
                'Adult'=>'成人',
                'Child'=>'儿童',
                'Infant'=>'婴儿',
                'Youth'=>'青年',
                'Senior'=>'老年人',
                '成年人'=>'成年人',
                '儿童'=>'儿童',
                '婴儿'=>'婴儿'
            ];

            $data = array();
            if(isset($cache[$gradeCode])){
                $ageBands = array();
                foreach ($cache[$gradeCode] as $k=>$v) {
                    if($date==$v['bookingDate']){//选中日期
                        $ageBands = $v['ageBands'];
                        break;
                    }
                }
                if(!empty($ageBands)){
                    foreach ($ageBands as $k=>$v) {
                        $band = array();
                        $description_name = isset($eto_list[$v['description']]) ? $eto_list[$v['description']] : $v['description'];
                        $band['title'] = $description_name;
                        $band['age'] = $v['age'];
                        $band['price'] = $v['price'];
                        $band['merchantNetPrice'] = $v['merchantNetPrice'];
                        $data[] = $band;
                    }
                }
            }
            return $data;
        }
    }

    //修改Viator套餐名称
    public function changeName ()
    {
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();
            $specsTable = Db::name('specsname');
            $where['code'] = $post['code'];
            $where['grade_code'] = $post['gradeCode'];
            $specs = $specsTable->where($where)->find();

            if($specs['new_name']==$post['title']){//无变动
                return $this->success('修改成功');
            }

            if(!empty($specs)){//已存在  修改
                $res = $specsTable->where($where)->Update([
                    'new_name'=>$post['title']
                ]);
            }else{//不存在则插入
                $data = array();
                $data['code'] = $post['code'];
                $data['grade_code'] = $post['gradeCode'];
                $data['specs_name'] = $post['specs_name'];
                $data['new_name'] = $post['title'];
                $res = $specsTable->insert($data);
            }
            if ($res) {
                return $this->success('修改成功');
            } else {
                return $this->error('修改失败');
            }
        }
    }

    //Viator意外下架商品，已处理  消除标记
    public function clearDropFlag(){
        $data = $this->request->request();
        $code = $data['code'];
        //修改状态
        $updateArr['accidentDrop'] = 0;
        $result = Db::name('goods')->where('code', $code)->update($updateArr);
        if (!empty($result)) {
            $res = [
                'code' => 200,
                'msg' => '已清除标识'
            ];
        }else{
            $res = [
                'code' => 400,
                'msg' => '操作失败'
            ];
        }
        return $res;
    }

    //把title里【】提取出来
    public function replaceTag(){
        $title_list = Db::name('goods')->field('goods_id,goods_name')->select();
        //正则
        $reg="/【{1}([\x{4e00}-\x{9fa5}])+】{1}/u";

        foreach ($title_list as $title){
            preg_match($reg,$title['goods_name'],$data);
            if(empty($data)){
                continue;
            }

            $tag_name=$data[0];
            // 1.判断类型是否存在 并获取id
            $tagstatus=Db::name('goodstag')->where(['tag_name'=>$tag_name])->find();
            if(empty($tagstatus)){
                Db::name('goodstag')->insert(['tag_name'=>$tag_name,'tag_status'=>1,'creattime'=>time(),'updatetime'=>time()]);
                $tag_id=Db::getLastInsID();
            }else{
                $tag_id=$tagstatus['tag_id'];
            }
            // 2.修改goods
            $data_list=[
                'goods_name'=>str_replace($tag_name,'',$title['goods_name']),
                'goodstag_id'=>$tag_id
            ];
            Db::name('goods')->where(['goods_id'=>$title['goods_id']])->update($data_list);
        }

        die('修改完毕');
    }

    //补充缺少的参考价格  脚本
    public function updatePrice()
    {
        $where['a.show'] = 2;
        $where['goods_status'] = 1;
        $where['merchantNetPrice'] = NULL;
        $goods = Db::name("goods")
            ->where($where)
            ->field("goods_id,code,price,merchantNetPrice")
            ->limit(500)
            ->select();

        echo "共有".count($goods)."个需要补全的商品";
        echo "<br>";

        if(!empty($goods)){
            foreach ($goods as $v) {
                $goods_md5 = Db::name("goods_backupsmd5")->where("code",$v['code'])->field("merchantNetPrice")->find();
                $price = $goods_md5['merchantNetPrice'];
                if(empty($price)){
                    echo $v['code']."取不到价格";
                    echo "<br>";
                    continue;
                }
                $data_list=[
                    'merchantNetPrice'=>$price
                ];
                $res = Db::name('goods')->where(['goods_id'=>$v['goods_id']])->update($data_list);
                if($res){
                    echo $v['code']."已补全";
                }else{
                    echo "【ERROR】".$v['code']."更改出错";
                    var_dump($res);
                }
                echo "<br>";
            }
        }

        die;
    }

    //手动刷新一个商品价格
    public function flushPrice(){
        $post = request()->post();
        $code = $post['code'];
        $viator = new Viator();

        //清除缓存
        cache($code.'price',array());
        cache($code.'type',array());
        //先刷商品的采购价和售价
        $viatorData = $viator->goodsDetail($code);
        $updData = [];
        if(!empty($viatorData['merchantNetPriceFrom'])){
            $updData['merchantNetPrice'] = $viatorData['merchantNetPriceFrom'];
        }
        if(!empty($viatorData['price'])){
            $updData['price'] = $viatorData['price'];
        }
        if(!empty($updData)) db('goods')->where(['code'=>$code])->update($updData);
        return $viator->timePrice($code);
    }

    //viator 折扣
    public function discount(){
        $discount=Db::name('viator_discount')->select();
        $this->assign('discount',$discount);
       return $this->fetch();
    }

    public function discountedit(){
        if($this->request->isPost()){
            $post=$this->request->post();
            $uid = $post['id'];
            $data=[
                'discount_num'=>$post['discount_num'],
                'status'=>$post['status'],
                'updatetime'=>time()
            ];
            $dsicount=Db::name('viator_discount')->where(['id'=>$uid])->update($data);
            if($dsicount){
                $arr =['code'=>1,'msg'=>'修改成功'];
            }else{
                $arr =['code'=>0,'msg'=>'修改失败'];
            }
            return $arr;
        }
        $uid=$this->request->param('uid');
        $dsicount=Db::name('viator_discount')->where(['id'=>$uid])->find();
        $this->assign('discount',$dsicount);
        return $this->fetch();
    }

    protected function delSpecsAndPerson($goods_id)
    {
        $goods = db("goods")->where("goods_id",$goods_id)->find();
        if(!empty($goods)){
            $specs = db("specs")->where(["goods_id"=>$goods_id,"specs_status"=>2])->column("specs_id");
            if(!empty($specs)){
                DB::startTrans();//开启事务
                try{
                    db("specs")->where(["goods_id"=>$goods_id,"specs_status"=>2,"specs_id"=>["in",$specs]])->delete();
                    db("person")->where(["specs_id"=>["in",$specs]])->delete();
                    db("personday")->where(["goods_id"=>$goods_id,"specs_id"=>["in",$specs]])->delete();
                    //提交事务
                    DB::commit();
                    return true;
                }catch(\PDOException $e){
                    //回滚事务
                    DB::rollback();
                    return false;
                }
            }
        }
    }

    public  function showspecs()
    {
        $get = request()->get();
        $goods = $specs = [];
        $goods_id = isset($get['id'])?$get['id']:0;
        $goods = db("goods")->find($goods_id);
        if(!empty($goods)) {
            $specs = db("specs")->where(["goods_id"=>$goods_id,"specs_status"=>1])->field("specs_name,specs_id")->select();
            if(!empty($specs)){
                $specs_id = [];
                foreach($specs as $key=>$value){
                    $specs[$key]['person'] = [];
                    $specs_id[] = $value['specs_id'];
                }
                if(!empty($specs_id)){
                    $starttime = date("Y-m-d",$goods['starttime']);
                    $endtime = date("Y-m-d",$goods['endtime']);
                    $personday = db("personday")->where(['goods_id'=>$goods_id,"specs_id"=>["in",$specs_id],"time"=>["between",[$starttime,$endtime]]])->order("time asc")->select();
                    if(!empty($personday)){
                        foreach ($personday as $k=>$v){
                            foreach ($specs as $kk=>$vv){
                                if($v['specs_id']==$vv['specs_id']){
                                    $specs[$kk]['person'][] = $v;
                                    break;
                                }
                            }
                        }
                    }
                }

            }
        }
        $this->assign("goods",$goods);
        $this->assign("specs",$specs);
        return $this->fetch();
    }

    public function modifySinglePerson()
    {
        $post = request()->post();
        $fail_data = [
            "code"=>1,
            "msg"=>"规格信息有误"
        ];
        if(!isset($post['person_id'])){
            return json($fail_data);
        }else{
            $id = $post['person_id'];
            $goods_id = $post['goods_id'];
            unset($post['person_id']);
            unset($post['goods_id']);

            $res = db("personday")->where("id",$id)->update($post);
            if($res===false){
                return json($fail_data);
            }
            //初始化当前商品日历缓存
            Cache::rm($goods_id.'rl');
            //更新商品价格区间
            $goods = db("goods")->find($goods_id);
            $price_data = (new G())->personDayMaxAndMinPrice($goods_id,date("Y-m-d",$goods['starttime']),date("Y-m-d",$goods['endtime']));
            if(!empty($goods['price_section'])){
                $price_section = explode("~",$goods['price_section']);
                if($price_section[0]!=$price_data['min'] || $price_section[1]!=$price_data['max']){
                    db("goods")->where("goods_id",$goods['goods_id'])->update([
                        'price_section'=>$price_data['min'].'~'.$price_data['max'],
                        'min_price'=>$price_data['min'],
                        'max_price'=>$price_data['max']
                    ]);
                }
            }else{
                db("goods")->where("goods_id",$goods['goods_id'])->update([
                    'price_section'=>$price_data['min'].'~'.$price_data['max'],
                    'min_price'=>$price_data['min'],
                    'max_price'=>$price_data['max']
                ]);

            }

            return json(['code'=>200,'msg'=>'修改成功']);

        }
    }

    public function delSinglePerson()
    {
        $post = request()->post();
        $fail_data = [
            "code"=>1,
            "msg"=>"删除失败"
        ];
        if(!isset($post['person_id'])){
            return json($fail_data);
        }else {
            $id = $post['person_id'];
            $personday = db("personday")->where("id",$id)->find();
            if(empty($personday)){
                return json($fail_data);
            }
            $goods = db("goods")->field("goods_id,starttime,endtime,price_section")->find($personday['goods_id']);
            //删除数据
            db("personday")->delete($id);
            $price_data = (new G())->personDayMaxAndMinPrice($personday['goods_id'],date("Y-m-d",$goods['starttime']),date("Y-m-d",$goods['endtime']));
            if(!empty($goods['price_section'])){
                $price_section = explode("~",$goods['price_section']);
                if($price_section[0]!=$price_data['min'] || $price_section[1]!=$price_data['max']){
                    db("goods")->where("goods_id",$goods['goods_id'])->update([
                        'price_section'=>$price_data['min'].'~'.$price_data['max'],
                        'min_price'=>$price_data['min'],
                        'max_price'=>$price_data['max']
                    ]);
                }
            }else{
                db("goods")->where("goods_id",$goods['goods_id'])->update([
                    'price_section'=>$price_data['min'].'~'.$price_data['max'],
                    'min_price'=>$price_data['min'],
                    'max_price'=>$price_data['max']
                ]);

            }
            //初始化当前商品日历缓存
            Cache::rm($goods['goods_id'].'rl');

            return json(['code'=>200,'msg'=>'删除成功']);
        }
    }

    //价格配置页面
    public function personsedit(){
        $goods_id= input('id');
        $goods = db("goods")->find($goods_id);
        $starttime = date("Y-m-d",$goods['starttime']);
        $endtime = date("Y-m-d",$goods['endtime']);
        $personday = db("personday")->where(["goods_id"=>$goods_id,'time'=>['between',[$starttime,$endtime]]])->order("id asc")->select();
        //按天封装数据
        $data = [];
        foreach ($personday as $value){
            $data[$value['time'].",".$value['specs_id']][] = $value;
        }
        $carTypeList = (new SDModel())->getCartypeList();
        $this->assign('goods',$goods)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime)
            ->assign('carTypeList',json_encode($carTypeList))
            ->assign('standard_id',input('standard_id'));
        return $this->fetch();
    }

    //价格配置ajax--personsedit页面
    public function personlog()
    {
        $post = request()->post();
        $param = json_decode($post['param'],true);

        //判断日期是否重叠
        $spec_id = $param['spec_id'];
        $time = $param['time'];
        $time_arr = explode(" - ",$time);
        $log_id = isset($param['log_id'])&&!empty($param['log_id'])?$param['log_id']:0;

        //查询当前套餐设置的所有价格配置
        $logs = db("personday_log")->where(['spec_id'=>$spec_id])->order("start_time asc")->select();
        $include_time = 0;
        if(!empty($logs) && empty($log_id)){
            $my_start = $time_arr[0];
            $my_end = $time_arr[1];
            foreach ($logs as $value){
                if($value['start_time']>=$my_start
                    && $value['end_time']<=$my_end){
                    return json(['code'=>-1,'msg'=>'不允许时间重叠']);
                }elseif($value['start_time']>=$my_start
                    && $value['end_time']>=$my_end
                    && $value['start_time'] <=$my_end){
                    return json(['code'=>-1,'msg'=>'不允许时间重叠']);
                }elseif($value['start_time']<=$my_start
                    && $value['end_time']>=$my_start
                    && $value['end_time'] <=$my_end){
                    return json(['code'=>-1,'msg'=>'不允许时间重叠']);
                }elseif($value['start_time']<=$my_start
                    && $value['end_time']>=$my_end){
                    $include_time++;
                    if($include_time>1){
                        return json(['code'=>-1,'msg'=>'不允许时间多次重叠']);
                    }
                }
            }
        }
        if($include_time==1){
            //包含时间范围内是否已经设置价格
            $day_where['specs_id'] = $spec_id;
            $day_where['time'] = ['in',$param['date']];
            $day_res = db("personday")->where($day_where)->find();
            if(!empty($day_res)){
                return json(['code'=>-1,'msg'=>'日期范围内已经设置过价格，请检查']);
            }
        }
        db::startTrans();
        try{
            $res = $this->insertPersonLogData($log_id,$param);
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $this->addPersonListByLog($spec_id,$param['specs'],$param['date']);

            db::commit();
            $is_add = isset($param['log_id'])&&!empty($param['log_id'])?false:true;
            return json(['code'=>200,'msg'=>'设置成功','data'=>['is_add'=>$is_add,'id'=>$res]]);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败','data'=>['is_add'=>false,'id'=>0]]);
        }

    }

    //插入日期记录
    protected function insertPersonLogData($log_id,$post)
    {
        $admin_id = Cookie::get('admin');
        $time_arr = explode(" - ",$post['time']);
        //specs快照
        foreach ($post['specs'] as $key=>$value){
            $person = db("person")->find($value['person_id']);
            $post['specs'][$key]['person_name'] = $person['person_name'];
            $post['specs'][$key]['minorder_num'] = $person['minorder_num'];
            $post['specs'][$key]['inc_order_num'] = $person['inc_order_num'];
            $post['specs'][$key]['person_num'] = $person['person_num'];
            $post['specs'][$key]['carType'] = $value['carType']??0;
            $post['specs'][$key]['recommendedCost'] = $value['recommendedCost']??0;
        }
        $insert = [
            'admin_id'=>$admin_id,
            'title'=>$post['time'],
            'spec_id'=>$post['spec_id'],
            'start_time'=>$time_arr[0],
            'end_time'=>$time_arr[1],
            'time_type'=>$post['time_type'],
            'time_value'=>$post['time_value'],
            'more_time'=>json_encode($post['more_time']),
            'date_json'=>json_encode($post['date']),
            'person_json'=>json_encode($post['specs'])
        ];
        if(!empty($log_id)){
            db("personday_log")
                ->where(['log_id'=>$log_id])
                ->update($insert);
        }else{
            db("personday_log")
                ->insert($insert);
            $log_id = db('person_log')->getLastInsID();
        }
        return $log_id;
    }

    //插入套餐记录
    protected function addPersonListByLog($spec_id,$specs,$date)
    {
        if(empty($specs))return false;
        if(empty($date))return false;
        $specinfo = db("specs")->find($spec_id);
        if(empty($specinfo))return false;
        //判断是否首次插入
        $del_res = db("personday")
            ->field("log_id,person_id,person_price,time,carType,recommendedCost")
            ->where(['specs_id'=>$spec_id,'time'=>['in',$date]])
            ->delete();
        //删除失败
        if($del_res===false)return false;
        $person_price = [];
        foreach ($specs as $key => $value) {
            $insertAll = [];
            $person = db("person")->find($value['person_id']);
            foreach ($date as $day) {
                $insertAll[] = [
                    'goods_id' => $specinfo['goods_id'],
                    'specs_id' => $spec_id,
                    'person_id' => $value['person_id'],
                    'person_name' => $person['person_name'],
                    'person_price' => $value['person_price'],
                    'person_num' => $person['person_num'],
                    'minorder_num' => $person['minorder_num'],
                    'inc_order_num' => $person['inc_order_num'],
                    'carType' => $value['carType'] ?? 0,
                    'recommendedCost' => $value['recommendedCost'] ?? 0,
                    'time' => $day,
                ];
            }
            //插入数据
            db("personday")->insertAll($insertAll);
            $person_price[] = $value['person_price'];
        }
        //更新价格
        if(!empty($person_price)){
            $this->updateGoodsPriceSection($specinfo['goods_id'],$person_price);
        }
    }

    //删除操作记录
    public function delPersonLog()
    {
        $post = request()->post();
        if(!isset($post['id']) || empty($post['id'])){
            return json(['code'=>-1,'msg'=>'删除失败']);
        }else{
            $log = db("personday_log")->find($post['id']);
            if(empty($log)){
                return json(['code'=>-1,'msg'=>'操作记录有误']);
            }else{
                $specinfo = db("specs")->find($log['spec_id']);
                db::startTrans();
                try{
                    db("personday_log")->delete($post['id']);
                    db("personday")->where('log_id',$post['id'])->delete();
                    //更新价格
                    $this->updateGoodsPriceSection($specinfo['goods_id']);
                    db::commit();
                    return json(['code'=>200,'msg'=>'删除成功']);
                }catch (Exception $e){
                    db::rollback();
                    return json(['code'=>-1,'msg'=>'删除失败']);
                }
            }
        }
    }

    //获取操作记录
    public function getPersondayLog()
    {
        $post = request()->post();
        if(!isset($post['goods_id']) || empty($post['goods_id'])){
            return json(['code'=>-1,'msg'=>'参数id有误']);
        }else{
            $log = db("personday_log p")
                ->join("specs s","s.specs_id=p.spec_id","LEFT")
                ->join("goods g","s.goods_id=g.goods_id","LEFT")
                ->where("g.goods_id",$post['goods_id'])
                ->field("p.*")->select();
            $logData = [];
            if(!empty($log)){
                $specids = array_unique(array_column($log,"spec_id"));
                foreach ($specids as $id){
                   $logData[$id] = [];
                   foreach ($log as $value){
                       if($id==$value['spec_id']){
                           $value['person_json'] = json_decode($value['person_json'],true);
                           $logData[$id][] = $value;
                       }
                   }
               }
            }

            return json(['code'=>200,'msg'=>'获取数据成功','data'=>$logData]);
        }
    }

    //删除规格
    public function delSpec()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $specinfo = db("specs")->find($post['id']);
            if(empty($specinfo)){
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
            db::startTrans();
            try{
                db("specs")->delete($post['id']);
                db("person")->where("specs_id",$post['id'])->delete();
                db("personday")->where("specs_id",$post['id'])->delete();
                db("personday_log")->where("spec_id",$post['id'])->delete();
                //更新价格
                $this->updateGoodsPriceSection($specinfo['goods_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }

    //删除人群
    public function delPerson()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $person = db("person")->find($post['id']);
            if(empty($person)){
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
            $specinfo = db("specs")->find($person['specs_id']);
            if(empty($specinfo)){
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
            db::startTrans();
            try{
                db("person")->where("person_id",$post['id'])->delete();
                db("personday")->where("specs_id",$person['specs_id'])->delete();
                $persondaylog = db("personday_log")->where("spec_id",$person['specs_id'])->delete();
                //更新价格
                $this->updateGoodsPriceSection($specinfo['goods_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }

    //更新商品价格
    protected function updateGoodsPriceSection($goods_id,$price=[])
    {
        $goods = db("goods")->find($goods_id);
        //获取目前商品的最低价和最高价
        $goods_stime = date("Y-m-d",$goods['starttime']);
        $goods_etime = date("Y-m-d",$goods['endtime']);
        $price_data = (new G())->personDayMaxAndMinPrice($goods_id,$goods_stime,$goods_etime);
        if(!empty($price_data) && $price_data['min']<=$price_data['max']){
            if(empty($price)){
                $min = $price_data['min'];
                $max = $price_data['max'];
            }else{
                //更新商品价格区间
                $min = min($price);
                $max = max($price);
                $min = $min <= $price_data['min']?$min:$price_data['min'];
                $max = $max >= $price_data['max']?$max:$price_data['max'];
            }
        }else{
            $min = $max = 0;
        }
        $price_section = $min.'~'.$max;
        $firstData = db("personday")->where(['goods_id'=>$goods_id,'time'=>$goods_stime])->find();
        $lastData = db("personday")->where(['goods_id'=>$goods_id,'time'=>$goods_etime])->find();
        if(!empty($firstData) && !empty($lastData)){
            $update_selltime = 0;
        }else{
            $update_selltime = 1;
        }
        //更新价格区间和价格套餐字段
        db('goods')->where('goods_id',$goods_id)->update([
            'price_section'=>$price_section,
            'update_selltime'=>$update_selltime,
            'min_price'=>$min,
            'max_price'=>$max
        ]);
        //初始化当前商品日历缓存
        cache($goods_id.'rl',null);
    }

    //刷新所有商品的价格设置
    public function freshGoodsPriceConfig()
    {
        ignore_user_abort();//关闭浏览器仍然运行
        set_time_limit(0);//后台运行
        Log::record("开始更新商品的价格配置提醒");
        $list = db("goods")->field("goods_id,starttime,endtime")->where("show",1)->select();
        var_dump(count($list));exit;
        if(!empty($list)){
            db::startTrans();
            try{
                foreach ($list as $key=>$value){
                    $goods_stime = date("Y-m-d",$value['starttime']);
                    $goods_etime = date("Y-m-d",$value['endtime']);
                    $firstData = db("personday")->where(['goods_id'=>$value['goods_id'],'time'=>$goods_stime])->find();
                    $lastData = db("personday")->where(['goods_id'=>$value['goods_id'],'time'=>$goods_etime])->find();
                    if(!empty($firstData) && !empty($lastData)){
                        $update_selltime = 0;
                    }else{
                        $update_selltime = 1;
                    }
                    //更新价格区间和价格套餐字段
                    db('goods')->where('goods_id',$value['goods_id'])->update([
                        'update_selltime'=>$update_selltime
                    ]);
                }

                db::commit();
                Log::record("更新成功");
                echo "success";
            }catch (Exception $e){
                db::rollback();
                Log::record("更新失败,原因是".json_encode($e));
                echo "error";
            }
        }

        Log::record("更新商品的价格配置提醒结束");
    }

    //更新价格配置记录 (老版本数据迁移)
    public function updatePersonLogByOldData()
    {
        //return json(['code'=>-1,'msg'=>'请联系管理员！']);exit;
        ignore_user_abort();
        set_time_limit(0);
        Log::record("更新价格配置记录开始");
        $specs = db("personday")->field("specs_id")->group("specs_id")->select();
        $specs_id = array_column($specs,'specs_id');
        $goods = db("specs s")
            ->join("goods g","g.goods_id=s.goods_id","left")
            ->field("s.specs_id,s.goods_id,g.starttime,g.endtime")
            ->where(['specs_id'=>['in',$specs_id]])
            ->select();
        $specList = array_unique(array_column($goods,"specs_id"));
        $data = [];
        foreach ($goods as $key=>$value){
            $value['startday'] = date("Y-m-d",$value['starttime']);
            $value['endday'] = date("Y-m-d",$value['endtime']);
            $data[$value['specs_id']] = $value;
        }
        var_dump($data);exit;
        db::startTrans();
        try{
            //生成对应的log_id
            foreach ($specs as $key=>$value){
                $stime = $data[$value['specs_id']]['startday'];
                $etime = $data[$value['specs_id']]['endday'];
                db("personday_log")->insert([
                    'title'=>$etime.' - '.$etime,
                    'spec_id'=>$value['specs_id'],
                    'start_time'=>$stime,
                    'end_time'=>$etime,
                    'time_type'=>0,
                    'time_value'=>'',
                    'person_json'=>''
                ]);
                $log_id = db("personday_log")->getLastInsID();
                db("personday")->where('specs_id',$value['specs_id'])->update([
                    "log_id"=>$log_id
                ]);
            }
            db::commit();
            Log::record("更新价格配置记录成功");
            echo "success";
        }catch (Exception $e){
            db::rollback();
            Log::record("更新价格配置记录失败,原因是".json_encode($e));
            echo "error";
        }
        Log::record("更新价格配置记录开始");
    }


    //上传附件
    public function savefile()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $typeid = $this->request->has('typeid') ? $this->request->param('typeid', 0, 'intval') : 2;
        $goods = db("goods")->where("goods_id",$id)->find();
        if(empty($goods)){
            return $this->error('商品信息有误');
        }
        if(request()->isPost()){
            $post = request()->post();
            if(!empty($post)){
                $model = new G();
                $post['updatetime'] = time();
                $post['up_updatetime'] = time();
                $res = $model->allowField(true)->where(['goods_id'=>$id])->update($post);
                if($res!==false){
                    return $this->success("修改成功");
                }else{
                    return $this->error("修改失败");
                }
            }else{
                return $this->error("修改失败");
            }
        }

        $goods['up_updatetime'] = !empty($goods['up_updatetime']) ? date("Y-m-d H:i",$goods['up_updatetime']) : '';

        $this->assign('goods',$goods);
        $this->assign('typeid',$typeid);
        return $this->fetch();
    }

    //下载附件
    public function uploadFile(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if($id==0){
            echo "文件路径错误";
            exit;
        }
        $goods = db("goods")->where('goods_id',$id)->field('up_filename,up_url')->find();
        $fileName = $goods['up_filename'];
        $url = $goods['up_url'];
        $info = get_headers($url, true);
        $size = $info['Content-Length'];
        header("Content-type:application/octet-stream");
        header("Content-Disposition:attachment;filename = " . $fileName);
        header("Accept-ranges:bytes");
        header("Accept-length:" . $size);
        readfile($url);
        exit;
    }

    //日历价格设置
    public function setgoodsprice(){
        $goods_id= input('id');
        $goods = db("goods")->find($goods_id);
        $starttime = date("Y-m-d",$goods['starttime']);
        $endtime = date("Y-m-d",$goods['endtime']);
        $personday = db("personday")->where(["goods_id"=>$goods_id,'time'=>['between',[$starttime,$endtime]]])->order("id asc")->select();
        //按天封装数据
        $data = [];
        foreach ($personday as $value){
            $data[$value['time'].",".$value['specs_id']][] = $value;
        }
        $carTypeList = (new SDModel())->getCartypeList();
        $this->assign('goods',$goods)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime)
            ->assign('carTypeList',json_encode($carTypeList))
            ->assign('standard_id',input('standard_id'));
        return $this->fetch();
    }
    //价格配置ajax--setgoodsprice页面
    public function ajaxsetgoodsprice()
    {
        $post = request()->post();
        $param = json_decode($post['param'],true);

        //判断日期是否重叠
        $spec_id = $param['spec_id'];
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $this->addPersonListByLog($spec_id,$param['specs'],$param['date']);

            db::commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败']);
        }

    }
    //批量删除价格配置
    public function delsetgoodsprice()
    {
        $post = request()->post();
        $param = json_decode($post['param'],true);

        //判断日期是否重叠
        $spec_id = $param['spec_id'];
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $this->deletePersonListByLog($spec_id,$param['date']);

            db::commit();
            return json(['code'=>200,'msg'=>'删除成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'删除失败']);
        }

    }
    //批量删除价格配置
    public function deletePersonListByLog($spec_id,$date){
        if(empty($date))return false;
        $specinfo = db("specs")->find($spec_id);
        if(empty($specinfo))return false;
        //判断是否首次插入
        $res = db("personday")
            ->where(['specs_id'=>$spec_id,'time'=>['in',$date]])
            ->delete();
        if($res===false) return false;
        $person_price = [];
        $list = db("personday")
            ->field("person_price")
            ->where(['goods_id'=>$specinfo['goods_id']])
            ->select();
        if(!empty($list)){
            $person_price = array_column($list,'person_price');
        }
        //更新价格
        $this->updateGoodsPriceSection($specinfo['goods_id'],$person_price);
    }
    //设置单日的套餐价格
    public function setSingleDayPrice()
    {
        $post = request()->post();

        $postdata = $post['data']??"";
        $goods_id = $post['goods_id']??0;
        if(empty($postdata) || empty($goods_id)){
            return json(['code'=>-1,'msg'=>'保存失败']);
        }

        $priceArr = json_decode($postdata,true);
        if(empty($priceArr)){
            return json(['code'=>-1,'msg'=>'保存失败']);
        }
        $person_price = [];
        db::startTrans();
        try{
            foreach ($priceArr as $value){
                $person_price[] = $value['price'];
                $personday = db("personday")->find($value['id']);
                if(!empty($personday) && $personday['person_price']!=$value['price']){
                    db("personday")->where('id',$value['id'])->update(['person_price'=>$value['price']]);
                }
            }
            db::commit();
            return json(['code'=>200,'msg'=>'保存成功']);
        }catch (Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'保存失败']);
        }

        //更新价格
        $this->updateGoodsPriceSection($goods_id,$person_price);
    }
    //配置价格套餐的车型
    public function setgoodscartype(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        //是新增操作
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post()['data'];

            Db::startTrans(); //启动事务
            try {
                foreach ($post as $key=>$value){
                    $postdata = $value['persondata']??[];
                    if(empty($postdata)){
                        continue;
                    }else{
                        foreach ($postdata as $k=>$v){
                            $car_type = $v['car_type']??0;
                            $person_id = $v['person_id']??0;
                            if(empty($person_id)){
                                continue;
                            }else{
                                db("person")->where('person_id',$person_id)->update(['car_type'=>$car_type]);
                                db("personday")->where('person_id',$person_id)->update(['carType'=>$car_type]);
                            }
                        }
                    }
                }
                Db::commit(); //提交事务
                return $this->success('更新套餐车型成功');
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error('更新套餐车型失败');
            }
        }else{
            $specs=Db::name('specs')->where("goods_id",$id)->where("specs_status",1)->where("specs_types",1)->select();
            if($specs){
                foreach ($specs as $key=>$value){
                    $specs[$key]['person']=Array();
                    $specs_id=$value['specs_id'];

                    $person=Db::name('person')->where("specs_id",$specs_id)->where("person_status",1)->select();

                    array_push($specs[$key]['person'],$person);
                }
                $this->assign('specs',$specs);
            }else{
                $this->assign('specs','');
            }
        }
        $carTypeList = (new SDModel())->getCarTypeList();
        //增加不配置车型的选择
        array_unshift($carTypeList,['cartype_id'=>0,'title'=>'无']);
        $this->assign('id',$id);
        $this->assign('carTypeList',$carTypeList);
        return $this->fetch();
    }


    //新 价格设置
    public function setproductprice(){
        $goods_id= input('id');
        $goods = db("goods")->find($goods_id);
        //判断是否存在默认套餐
        $this->setDefaultSpec($goods_id);

        $exchangeData = db("exchange")->select();
        $exchange = [];
        foreach ($exchangeData as $k=>$v) {
            $exchange[$v['currency_code']] = $v['exchange_rate'];
        }
        $city = db("city")->where("id",$goods['city_id'])->field("groupid")->find();
        if($city['groupid']==48){
            $currency = "$";
            $currencyCode = "USD";
            $currencyName = "美元";
            $exchangeNum = $exchange["USD"];
        }elseif($city['groupid']==51){
            $currency = "C$";
            $currencyCode = "CAD";
            $currencyName = "加元";
            $exchangeNum = $exchange["CAD"];
        }else{
            $currency = "￥";
            $currencyCode = "CNY";
            $currencyName = "人民币";
            $exchangeNum = 1;
        }

        //派单价格
        $carPriceArr = ['f_cost'=>0,'s_cost'=>0,'t_cost'=>0];
        $standard = db("standard")->where("goods_id",$goods_id)->find();
        if(!empty($standard)){
            //查询已配置过的派单价格
            $psection = db("psection")
                ->alias("p")
                ->join("standardtrip s","p.product_id=s.trip_id","left")
                ->where("s.sid",$standard['id'])
                ->field("p.*")
                ->select();

            if(!empty($psection)){
                foreach ($psection as $key=>$value) {
                    $section_json = json_decode($value['section_json'],true);
                    $price = 0;
                    foreach ($section_json as $k=>$v) {
                        $price += intval($v);
                    }
                    if($value['car_type']==1){
                        $carPriceArr['f_cost'] = $price;
                    }elseif($value['car_type']==10){
                        $carPriceArr['s_cost'] = $price;
                    }elseif($value['car_type']==20){
                        $carPriceArr['t_cost'] = $price;
                    }
                }
            }
        }

        $starttime = date("Y-m-d",$goods['starttime']);
        $endtime = date("Y-m-d",$goods['endtime']);
        $personday = db("personday")->where(["goods_id"=>$goods_id,'time'=>['between',[$starttime,$endtime]]])->order("id asc")->select();
        //按天封装数据
        $data = [];
        foreach ($personday as $value){
            $data[$value['time'].",".$value['specs_id']][] = $value;
        }
        $carTypeList = (new SDModel())->getCartypeList();
        $this->assign('goods',$goods)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime)
            ->assign('carTypeList',json_encode($carTypeList))
            ->assign('standard_id',input('standard_id'))
            ->assign('currency',$currency)
            ->assign('currencyCode',$currencyCode)
            ->assign('currencyName',$currencyName)
            ->assign('exchangeNum',$exchangeNum)
            ->assign('carPriceArr',$carPriceArr);
        //展示额外价格
        $extra_cost = $this->getExtraCostByGoods($goods_id);
        $this->assign("extra_cost",$extra_cost);
        return $this->fetch();
    }

    //获取利率、酒店、门票信息
    public function getPriceSetData(){
        $post = request()->post();
        if(empty($post['goods_id'])){
            return $this->error("参数id有误");
        }
        $goods_id = $post['goods_id'];
        $goodsData = db("goods")
            ->alias("g")
            ->join("product p","g.goods_tcode=p.item_num","left")
            ->where("goods_id",$goods_id)
            ->field("p.id as product_id,g.goods_tcode,g.hotel_price_json,g.vehicle_rate,g.hotel_rate,g.ticket_rate,g.extra_rate,g.extra_fee,g.extra_fee_desc")
            ->find();

        if(!empty($goodsData['hotel_price_json'])){
            $goodsData['hotel_price_json'] = json_decode($goodsData['hotel_price_json'],true);
        }

        $resTicketData = [];
        if(!empty($goodsData['product_id'])){
            $poiMode = new Poi();
            $ticketData = $poiMode->getProductTicket($goodsData['product_id']);
            foreach ($ticketData as $k=>$v) {
                foreach ($v['ticket'] as $vv){
                    if($vv['default']==1){
                        $resTicketData[] = $vv;
                    }
                }
            }
        }else{
            return $this->error("请绑定产品编码");
        }

        $exchange = db("exchange")->select();

        $resData = [
            'goods'=>$goodsData,
            'ticket'=>$resTicketData,
            'exchange'=>$exchange
        ];

        return $this->success('ok','',$resData);
    }

    //设置商品利率/门票/酒店信息......
    public function setgoodsinfo()
    {
        $goods_id= input('id');
        $goods = db("goods")->find($goods_id);
        if(empty($goods_id) || empty($goods)) $this->error("商品信息不存在");

        //获取关联的产品信息
        $ticketList = [];
        $ticketTotalCost = 0;
        $p_code = $goods['goods_tcode']??"";
        if(!empty($p_code)){
            $product = db("product")->where(['item_num'=>$p_code])->order("id desc")->find();
            if(!empty($product)){
                //获取门票相关信息
                $scheduleData =  (new SDModel())->getProductScheduleData($product['id']);
                $hasTicketPoiId = [];
                foreach ($scheduleData as $key=>$value){
                    foreach ($value['children'] as $k=>$v){
                        if($v['ticket_status']==1){
                            $hasTicketPoiId[] = $v['poiid'];
                        }
                    }
                }

                //获取门票列表
                if(!empty($hasTicketPoiId)){
                    $ticketList = (new SDModel())->getSectionTicketData($hasTicketPoiId);
                    foreach ($ticketList as $ticket_k=>$ticket_v){
                        $ticketTotalCost += $ticket_v['unitBase']['amount'];
                    }
                }
            }
        }
        $hotel_price = !empty($goods['hotel_price_json'])?json_decode($goods['hotel_price_json'],true):[];
        $this->assign("goods",$goods)
            ->assign("ticketList",$ticketList)
            ->assign("ticketTotalCost",$ticketTotalCost)
             ->assign("hotel_price",$hotel_price);
        $city = db("city")
            ->where("status",1)
            ->where(['type'=>'city','kbx_id'=>['neq','']])
            ->field("id,kbx_id,name,eng_name")
            ->select();
        $this->assign("cityList",$city);
        $this->assign("cityJson",json_encode($city));
        $hotelLevel = [
            ['level'=>5,'levelName'=>'5星级'],
            ['level'=>4,'levelName'=>'4星级'],
            ['level'=>3,'levelName'=>'3星级'],
            ['level'=>2,'levelName'=>'2星级'],
            ['level'=>1,'levelName'=>'1星级'],
        ];
        $this->assign("level",$hotelLevel);
        $this->assign("levelJson",json_encode($hotelLevel));

        $startDay = [];
        $product_id = $product['id']??0;
        $psection = db("pschedule")
            ->field("id,title")
            ->where(['groupid'=>$product_id])
            ->order('displayorder asc')
            ->select();
        if(!empty($psection)){
            foreach ($psection as $key=>$value){
                $startDay[] = [
                    'day'=>$key+1,
                    'dayName'=>'第'.($key+1).'天',
                ];
            }
        }
        $this->assign("startDay",$startDay);
        $this->assign("startDayJson",json_encode($startDay));

        //展示额外价格
        $extra_cost = $this->getExtraCostByGoods($goods_id);
        $this->assign("extra_cost",$extra_cost);
        return $this->fetch();
    }
    //获取额外成本
    protected function getExtraCostByGoods($goods_id)
    {
        $extra_cost = [];
        $goods = db('goods')->find($goods_id);
        if(empty($goods) || empty($goods_id) || empty($goods['goods_tcode'])) return $extra_cost;
        $product = db('product')->where(['item_num'=>$goods['goods_tcode']])->find();
        if(empty($product)) return $extra_cost;
        //额外费用 按司导分段进行设置
        $psection = db('psection')->where(['product_id'=>$product['id']])->find();
        if(!empty($psection['section_json'])){
            $section_json = json_decode($psection['section_json'],true);
            $extra_cost = array_fill(0,count($section_json),['cost'=>0,'desc'=>'']);
        }
        $_extra_cost = !empty($goods['extra_fee'])?explode(',',$goods['extra_fee']):[];
        $_extra_desc = !empty($goods['extra_fee_desc'])?explode('|',$goods['extra_fee_desc']):[];
        if(!empty($extra_cost) && !empty($_extra_cost)){
            foreach ($_extra_cost as $key=>$value){
                $extra_cost[$key]['cost'] = $value??0;
                $extra_cost[$key]['desc'] = $_extra_desc[$key]??"";
            }
        }
        return $extra_cost;
    }
    //保存商品利率
    public function savePriceRate()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $goods = db("goods")->find($id);
        if(empty($goods)) $this->error("保存失败，请刷新后重试");
        $hotelArr = $post['postdata']??[];
        $extraArr = $post['extradata']??[];
        if(!empty($hotelArr)){
            $hotelArr = json_decode($hotelArr,true);
        }
        if(!empty($hotelArr)){
            foreach ($hotelArr as $key=>$value){
                $city = db("city c")->where(["kbx_id"=>$value['kbxCityId']])->find();
                if($city['groupid']==48){
                    $hotelArr[$key]['cost']['currency'] = "USD";
                    $hotelArr[$key]['cost']['currSymbol'] = "$";
                    $hotelArr[$key]['cost']['currName'] = "美元";
                }elseif($city['groupid']==51){
                    $hotelArr[$key]['cost']['currency'] = "CAD";
                    $hotelArr[$key]['cost']['currSymbol'] = "C$";
                    $hotelArr[$key]['cost']['currName'] = "加元";
                }
            }
        }
        if(!empty($extraArr)){
            $extraArr = json_decode($extraArr,true);
        }
        $extra_fee = [];
        $extra_fee_desc = [];
        if(!empty($extraArr)){
            foreach ($extraArr as $key=>$value){
                $ex_cost = !empty($value['cost'])?$value['cost']:0;
                $extra_fee[] = $ex_cost;
                $extra_fee_desc[] = $value['desc'];
            }
        }
        $extra_fee = implode(',',$extra_fee);
        $extra_fee_desc = implode('|',$extra_fee_desc);
        //保存酒店配置
        db('goods')->where(['goods_id'=>$id])->update(['hotel_price_json'=>json_encode($hotelArr)]);

        //保存利率
        $vehicle_rate = $post['vehicle_rate']??0;
        $hotel_rate = $post['hotel_rate']??0;
        $ticket_rate = $post['ticket_rate']??0;
        $extra_rate = $post['extra_rate']??0;

        if($vehicle_rate<1 || $hotel_rate<1 || $ticket_rate<1 ||$extra_rate<1){
            $this->error("请检查利率不能小于1");
        }

        $update['vehicle_rate'] = $vehicle_rate;
        $update['hotel_rate'] = $hotel_rate;
        $update['ticket_rate'] = $ticket_rate;
        $update['extra_rate'] = $extra_rate;
        $update['extra_fee'] = $extra_fee;
        $update['extra_fee_desc'] = $extra_fee_desc;

        $res = db('goods')->where(['goods_id'=>$id])->update($update);
        if($res!==false){
            //修改利率刷新价格
            //当三种修改了任意一种 就需要刷新价格
            if($vehicle_rate==$goods['vehicle_rate'] &&
                $hotel_rate==$goods['hotel_rate'] &&
                $ticket_rate==$goods['ticket_rate'] &&
                $extra_rate==$goods['extra_rate'] &&
                $extra_fee==$goods['extra_fee']
            ){
                // nothing ....
            }else{
                (new GModel())->refreshGoodsTotalPrice($id);
                //刷新价格区间
                $this->updateGoodsPriceSection($id);
            }
            //修改了酒店利率 需要刷新酒店的售价
            if($hotel_rate!=$goods['hotel_rate']){
                (new GModel())->updHotelCost($id,$hotel_rate);
            }
            $this->success("保存成功");
        }else{
            $this->error("保存失败");
        }
    }

    //关联产品编号
    public function setgoodsprocode()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $goods = db("goods")->find($id);
        if(empty($goods)) $this->error("设置失败，请刷新后重试");
        $code = $post['code']??"";
        $code = trim($code);//去除左右空格
        $product = db("product")->where(['item_num'=>$code])->find();
        if(empty($product)) $this->error("未检测到匹配的产品，请检查产品编码后重试");

        $res = db('goods')->where(['goods_id'=>$id])->update(['goods_tcode'=>$code]);
        if($res!==false){
            $this->success("设置成功");
        }else{
            $this->error("设置失败");
        }
    }

    //核算价格
    public function calculateprice()
    {
        $goods_id= input('id');
        $goods = db("goods")->find($goods_id);
        if(empty($goods_id) || empty($goods)) $this->error("商品信息不存在");
        //获取税率
        $exchange_rate = db("exchange")->select();
        $this->assign("goods",$goods);
        $this->assign("exchange_rate",$exchange_rate);
        return $this->fetch();
    }

    //新  价格配置ajax--setgoodsprice页面
    public function ajaxsetproductprice()
    {
        $post = request()->post();
        $param = json_decode($post['param'],true);
        //判断日期是否重叠
        $spec_id = $param['spec_id'];
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $res = $this->newAddPersonListByLog($spec_id,$param['specs'],$param['date'],$param['more_btn'],$param['hotels']);

            if(!$res){
                db::rollback();
                return json(['code'=>-1,'msg'=>'设置失败']);
            }

            db::commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败'.$e]);
        }
    }

    //新 插入套餐记录
    protected function newAddPersonListByLog($spec_id,$specs,$date,$more_btn,$hotels)
    {
        if(empty($specs))return false;
        if(empty($date))return false;
        $specinfo = db("specs")->find($spec_id);
        if(empty($specinfo))return false;

        $hotel_price_json = [];
        if($more_btn==1){
            $goods_id = $specinfo['goods_id'];
            $goodsData = db("goods")->where("goods_id",$goods_id)->field("hotel_price_json")->find();
            $hotelData = json_decode($goodsData['hotel_price_json'],true);
            foreach ($hotels as $k=>$v) {
                $hotelData[$k]['cost']['amount'] = $v['hotelCost'];
                $hotelData[$k]['price'] = $v['hotelCostToPrice'];
            }
            $hotel_price_json = $hotelData;
        }

        $vehicle_type = $more_btn==1 ? 2 : 1;
        if($specinfo['auto_flag']==0 || $specinfo['vehicle_type']!==$vehicle_type){
            $del_res = db("personday")->where(['specs_id'=>$spec_id])->delete();
            $del_res1 = db("person")->where(['specs_id'=>$spec_id])->delete();
            //删除失败
            if($del_res===false)return false;
            if($del_res1===false)return false;

            db("specs")
                ->where("specs_id",$spec_id)
                ->update([
                    'vehicle_type'=>$vehicle_type,
                    'auto_flag'=>1,
                    'updatetime'=>time()
                ]);
            //生成新的规格
            foreach ($specs as $key => $value) {
                $insertData = [
                    'specs_id' => $spec_id,
                    'person_name' => $value['person_name'],
                    'person_price' => $value['person_price'],
                    'person_num' => 99,
                    'minorder_num' => $value['minorder_num'],
                    'inc_order_num' => $value['inc_order_num'],
                    'car_type' => $value['carType'] ?? 0,
                    'creattime' => time(),
                    'updatetime' => time(),
                    'people_num' => $value['people_num'],
                ];
                db("person")->insert($insertData);
                $person_id = db("person")->getLastInsID();
                $specs[$key]['person_id'] = $person_id;
            }
        }else{
            $del_res = db("personday")->where(['specs_id'=>$spec_id,'time'=>['in',$date]])->delete();
            //删除失败
            if($del_res===false)return false;

            if($vehicle_type==1){//纯包车  5、7、12
                foreach ($specs as $key => $value) {
                    $where['specs_id'] = $spec_id;
                    $where['car_type'] = $value['carType'];
                    $person = db("person")->where($where)->find();
                    $specs[$key]['person_id'] = $person['person_id'];
                }
            }else{//包含酒店门票  1-6人出行
                foreach ($specs as $key => $value) {
                    $where['specs_id'] = $spec_id;
                    $where['people_num'] = $value['people_num'];
                    $person = db("person")->where($where)->find();
                    $specs[$key]['person_id'] = $person['person_id'];
                }
            }
        }

        $person_price = [];
        foreach ($specs as $key => $value) {
            $insertAll = [];
            $person = db("person")->find($value['person_id']);
            foreach ($date as $day) {
                $insertAll[] = [
                    'goods_id' => $specinfo['goods_id'],
                    'specs_id' => $spec_id,
                    'person_id' => $value['person_id'],
                    'person_name' => $person['person_name'],
                    'person_price' => $value['person_price'],
                    'person_num' => $person['person_num'],
                    'minorder_num' => $person['minorder_num'],
                    'inc_order_num' => $person['inc_order_num'],
                    'carType' => $value['carType'] ?? 0,
                    'recommendedCost' => $value['recommendedCost'] ?? 0,
                    'time' => $day,
                    'vehicle_cost' => $value['vehicle_price']??0,
                    'hotel_cost' => $value['hotel_price']??0,
                    'ticket_cost' => $value['ticket_price']??0,
                    'extra_cost' => $value['extra_price']??0,
                    'hotel_json' => !empty($hotel_price_json)?json_encode($hotel_price_json):'',
                ];
            }

            //插入数据
            db("personday")->insertAll($insertAll);
            $person_price[] = $value['person_price'];
        }
        //更新价格
        if(!empty($person_price)){
            $this->updateGoodsPriceSection($specinfo['goods_id'],$person_price);
        }
        return true;
    }

    //默认生成套餐A
    public function setDefaultSpec($goods_id)
    {
        //检测是否存在商品
        $goods = db("goods")->find($goods_id);
        if(empty($goods_id) || empty($goods)) return false;
        //检测是否已经存在套餐 如存在直接跳过
        $specs = db("specs")->where(['goods_id'=>$goods_id])->find();
        if(!empty($specs)) return false;
        //生成新套餐
        $res = db('specs')->insert([
            "goods_id"=>$goods_id,
            "specs_name"=>"套餐A",
            "specs_status"=>1,
            "auto_flag"=>1,
            "creattime"=>time(),
            "updatetime"=>time(),
        ]);

        return $res;
    }

    //通过商品code 查询产品 并关联标品
    protected function linkStandardByGoodsTcode($goods_tcode,$standardId)
    {
        trace('我在生成标品关联行程');
        if(!empty($goods_tcode)){
            $productInfo = db('product')->where('item_num',$goods_tcode)->find();
            if(!empty($productInfo)){
                $gt_model = new GT();
                $product = $gt_model->getTripData($productInfo['id']);
                $lineSummary = $gt_model->getTripSummary($product);
                $toursLineTitle = !empty($lineSummary) ? implode("\n",$lineSummary) : '';
                $sTripData = [];
                $sTripData['sid'] = $standardId;
                $sTripData['trip_id'] = $productInfo['id'];
                $sTripData['days'] = $product['days'];
                $sTripData['startCityId'] = $product['start_city'];
                $sTripData['toursLineTitle'] = $toursLineTitle;
                db("standardtrip")->insert($sTripData);
            }
        }
    }

    //上架商品通知到微信
    public function checkGoodsStatusToKbx($req=[])
    {
        if(empty($req['goods_status'])) return false;
        //判断是否为上架状态
        if($req['goods_status']=='1'){
//            (new Common())->sendUpGoodsMsgToWx($req['goods_id'],$admin_id);
            $this->addUpdateGoodsNoticeLog($req['id']??$req['goods_id'],[],1);//操作员修改订单上架状态 提醒OTA
        }
    }

    //商品更新修改OTA提醒
    public function updOTANotice()
    {
        $post = request()->post();
        $id = $post['id']??0;
        if(empty($id)) return $this->result([],0,'商品ID错误','json');
        $goods = db('goods')->find($id);
        if(empty($goods)) return $this->result([],0,'商品不存在','json');

        $allow_fields = ['is_ctrip_notice','is_fliggy_notice','is_mafengwo_notice'];
        if(!in_array($post['notice_column'],$allow_fields)) return $this->result([],0,'更新字段有误','json');
        $notice_value = $post['notice_value']??0;
        $res = db('goods')->where('goods_id',$id)->update([$post['notice_column']=>$notice_value]);
        if($res!==false){
            //添加反馈操作日志
            $index = array_search($post['notice_column'],$allow_fields);
            $this->addUpdateGoodsNoticeLog($id,[],2,$index+1);
            return $this->result($post,200,'更新成功','json');
        }else{
            return $this->result([],0,'修改失败','json');
        }

    }
    //修改商品信息创建提醒事项

    /**
     * @param $data 数据集合
     * @param $type 提醒类型 1发出提醒 2反馈
     * @param $channel 渠道类型 1携程 2飞猪 3马蜂窝 0无渠道
     * @return int|string
     */
    public function addUpdateGoodsNoticeLog($id,$data=[],$type=1,$channel=0)
    {
        if(empty($id)) return false;
        $admin_id = Cookie::get('admin');
        $adminInfo = (new Common())->getAdminInfo($admin_id);
        $goods = db('goods')->find($id);
        if(empty($id) || empty($goods)) return false;

        //判断是提醒还是反馈
        if($type==1){
            $title = '修改商品信息通知OTA';
            $content = $adminInfo['nickname'].'修改了商品【'.$goods['goods_name'].'】';
        }else{
            $channel_name = $this->getOTAChannelName($channel);
            $title = 'OTA_'.$channel_name.'完成修改';
            $content = $adminInfo['nickname'].'完成了OTA_'.$channel_name.'的商品【'.$goods['goods_name'].'】的信息同步';
            //同一平台同一产品 限制十分钟只发一次
            $limit_time = 10*60;
            $exist_log = db('update_goods_notice_log')->where([
                'goods_id'=>$id,
                'channel'=>$channel,
                'create_time'=>['egt',time() - $limit_time]
            ])->find();
        }
        //具体操作细节
        if(!empty($data)){
            $content .= implode(',',$data);
        }

        $res = db('update_goods_notice_log')->insert([
            'title'=>$title,
            'content'=>$content,
            'goods_id'=>$id,
            'admin_id'=>$admin_id,
            'type'=>$type,
            'channel'=>$channel,
            'create_time'=>time(),
        ]);
        //保存成功且需要对进行订单同步消息
        if($res){
            if($type==1){
                $this->pushNoticeData($id,$adminInfo['nickname']);
                //同时将三个平台的状态修改为需要更新
                db('goods')->where('goods_id',$id)->update([
                    'is_ctrip_notice'=>1,
                    'is_fliggy_notice'=>1,
                    'is_mafengwo_notice'=>1,
                ]);
            }elseif($type==2){
                if(empty($exist_log)){
                    //同步到群消息
                    (new Common())->sendUpGoodsMsgToWx($id,$admin_id,$channel_name);
                }
            }

        }
        return $res;
    }

    public function getOTAChannelName($channel)
    {
        $name = '';
        switch ($channel){
            case 1:
                $name = '携程';break;
            case 2:
                $name = '飞猪';break;
            case 3:
                $name = '马蜂窝';break;
            default:
                $name = '官方';break;
        }
        return $name;
    }

    public function goodsNoticeLog()
    {
        $goods_id = input('id',30675);
        $list = $this->getGoodsNoticeLogList($goods_id);

        $this->assign('list',$list);
        return $this->fetch();
    }
    public function getGoodsNoticeLogList($goods_id)
    {
        $logs = db('update_goods_notice_log l')
            ->join('admin a','a.id=l.admin_id','left')
            ->field('l.*,a.nickname')
            ->where('l.goods_id',$goods_id)
            ->order('l.create_time desc')
            ->select();
        foreach ($logs as $key=>$value){
            $logs[$key]['create_time'] = date('m-d H:i',$value['create_time']);
            $logs[$key]['channel_name'] = $this->getOTAChannelName($value['channel']);
        }

        return $logs;
    }

    //viator商品提醒配置
    public function othergoodsnotice()
    {
        $goods_id = input('id',0);
        if(empty($goods_id)) return $this->error('商品ID有误');
        $goods = db('goods')->where('show',2)->find($goods_id);
        if(empty($goods)) return $this->error('viator商品不存在');
        $data = db('goods_notice')->where('goods_id',$goods_id)->find();
        if(!empty($data)){
            $data['assembleimgs'] = array_values(array_filter(explode(',',$data['assemble_address_img'])));
            $data['ticketimgs'] = array_values(array_filter(explode(',',$data['exchange_ticket_img'])));
            $pick_up_address_json = '';
            $assemble_address_json = '';
            if(!empty($data['pick_up_address_json'])){
                $pick_up_address_json = json_decode($data['pick_up_address_json'],true);
                foreach ($pick_up_address_json as $key=>$value){
                    $pick_up_address_json[$key]['format'] = json_encode($value['format']);
                }
            }
            if(!empty($data['assemble_address_json'])){
                $assemble_address_json = json_decode($data['assemble_address_json'],true);
                foreach ($assemble_address_json as $key=>$value){
                    $assemble_address_json[$key]['format'] = json_encode($value['format']);
                }
            }
            $data['pick_up_address_json'] = $pick_up_address_json;
            $data['assemble_address_json'] = $assemble_address_json;
        }
        $this->assign('id',$goods_id);
        $this->assign('data',$data);
        //货币单位
        $currencyList = (new Common())->getCurrencyListByCity();
        $this->assign('currencyList',$currencyList);
        return $this->fetch();
    }

    //保存新的viator商品提醒信息
    public function updothergoodsnotice()
    {
        $post = request()->post();
        $goods_id = input('id',0);
        if(empty($goods_id)) return $this->result([],0,'商品ID有误');
        $goods = db('goods')->field('goods_tcode')->where('show',2)->find($goods_id);
        if(empty($goods)) return $this->result([],0,'viator商品不存在');
        //去除多余的键值
        unset($post['pick_up_time'],$post['pick_up_address'],$post['pick_up_address_format']);
        unset($post['assemble_time'],$post['assemble_address'],$post['assemble_address_format'],$post['assemble_address_img']);

        $data = db('goods_notice')->where('goods_id',$goods_id)->find();
        $post['assemble_address_img'] = $post['assemble_address_img']??[];
        $post['assemble_address_img'] = implode(',',$post['assemble_address_img']);
        $post['exchange_ticket_img'] = $post['exchange_ticket_img']??[];
        $post['exchange_ticket_img'] = implode(',',$post['exchange_ticket_img']);
        $post['pick_up_address_json'] = str_replace('replace_and','&',$post['pick_up_address_json']);
        $post['assemble_address_json'] = str_replace('replace_and','&',$post['assemble_address_json']);
        if(empty($data)){
            //新增
            $post['goods_id'] = $goods_id;
            $post['goods_code'] = $goods['goods_tcode'];
            $res = db('goods_notice')->insert($post);
        }else{
            //更新
            $res = db('goods_notice')->where('goods_id',$goods_id)->update($post);
        }

        if($res!==false){
            return $this->result([],200,'更新成功');
        }else{
            return $this->result([],0,'更新失败');
        }
    }

    //封装通知OTA数据
    public function pushNoticeData($goods_id,$adminName)
    {
        $where['g.goods_id'] = $goods_id;
        $goods = db('goods g')
            ->join('city c','c.id=g.city_id','left')
            ->join('product p','p.item_num=g.goods_tcode','left')
            ->field('g.goods_id,g.goods_name,p.name as product_name,
            c.name as city_name,g.supplier_id,g.goods_tcode,supplier_item_code')
            ->where($where)
            ->find();
        if(empty($goods_id) || empty($goods)) return false;

        $supplier_name = '';
        $supplierList = (new Common())->getSupplierList();
        foreach ($supplierList as $supplier){
            if($goods['supplier_id']==$supplier['id']){
                $supplier_name = $supplier['name'];break;
            }
        }
        $product_name = empty($goods['product_name'])?(empty($goods['goods_name'])?'':$goods['goods_name']):$goods['product_name'];

        $data = [
            'product'=>[
                'code'=>$goods['goods_tcode'],
                'city'=>$goods['city_name'],
                'supplier'=>$supplier_name,
                'adminName'=>$adminName,
                'productName'=>$product_name,
                'codeBySupplier'=>$goods['supplier_item_code'],
            ]
        ];
        (new KbxOrder())->addOTANoticeItem($data);
    }

    //修改商品信息直接上架到B端平台
    public function pushStandardInfoToESbyUpdateGoods($standard_id,$show_tob)
    {
        if(empty($standard_id)) return false;
        //更新产品状态为未审核
        $standard = db('standard')->find($standard_id);
        $standardtrip = db('standardtrip')->where('sid',$standard_id)->find();
        if(!empty($standardtrip['trip_id'])){
            if($show_tob > 0){
                $gt_model = new GT();
                $product = $gt_model->getTripData($standardtrip['trip_id']);
                $lineSummary = $gt_model->getTripSummary($product);
                $toursLineTitle = !empty($lineSummary) ? implode("\n",$lineSummary) : '';
                //行程路线
                db('standardtrip')->where('trip_id',$standardtrip['trip_id'])->update([
                    'toursLineTitle'=>$toursLineTitle
                ]);
                //通过审核的状态
                db('product')->where('id',$standardtrip['trip_id'])->update([
                    'check_status'=>2
                ]);
                $productInfo = db('product')->where('id',$standardtrip['trip_id'])->find();
                if(!empty($productInfo['base_price_mode'])){
                    //基价模式更新产品的售价
                    (new ProController())->updateProductBasePriceSection($standardtrip['trip_id']);
                }elseif(!empty($productInfo['new_price_flag'])){
                    //产品价格模式更新产品的售价
                    (new ProController())->updateProductPriceSection($standardtrip['trip_id']);
                }
                //es 更新该商品
                (new Esapi())->refreshStandardDataToES($standard_id);
                //通知相应供应商上架该商品
                (new KbxOrder())->putOnSaleNotifyToKbx($standard_id);
            }else{
                //es 删除该商品
                (new Esapi())->delStandardDoc($standard_id);
                //通知相应供应商下架该商品
                (new KbxOrder())->pullOffShelvesNotifyToKbx($standard_id);
                //服务号通知供应商下架通知
                //(new KbxOrder())->sendProductOffAlertNotify($standard);
            }

        }else{
            //不存在关联产品的标品
            if($show_tob > 0){
                //es 更新该商品
                (new Esapi())->refreshStandardDataToES($standard_id);
                //通知相应供应商上架该商品
                (new KbxOrder())->putOnSaleNotifyToKbx($standard_id);
                //首次审核产品上架通知
                (new SDModel())->setOnSaleNoticeAtFirst($standard_id);
            }else{
                //es 删除该商品
                (new Esapi())->delStandardDoc($standard_id);
                //通知相应供应商下架该商品
                (new KbxOrder())->pullOffShelvesNotifyToKbx($standard_id);
                //服务号通知供应商下架通知
                //(new KbxOrder())->sendProductOffAlertNotify($standard);
            }
        }

    }

    //增加批量拉取viator商品的图片
    public function batchViatorImagesByCodes(Request $request)
    {
        return $this->fetch();
    }
    //检测输入的viatorCode是否生效
    public function verifyVaitorCodes(Request $request)
    {
        if(!$request->isPost()) return $this->error('请以POST方式提交');
        $viatorCodes = $request->post('viatorCodes','');
        $viatorCodes = explode(',',$viatorCodes);
        if(empty($viatorCodes)) return $this->error('请填写viatorCodes');
        foreach ($viatorCodes as $k=>$v){
            $viatorCodes[$k] = trim($v);
            $viatorCodesArr[$k] = '"'.trim($v).'"';
        }
        $order_expression = new Expression('field(code,'.implode(',',$viatorCodesArr).')');
        $viatorGoods = db('goods')->where([
            'show'=>2,
            'code'=>['in',$viatorCodes]
        ])->order($order_expression)->select();
        $correntViatorCodes = [];
        foreach ($viatorCodes as $key=>$value){
            $viatorCodes[$key] = ['viatorCode'=>$value,'viatorName'=>'匹配失败'];
            foreach ($viatorGoods as $k=>$v){
                if($v['code']==$value){
                    $viatorCodes[$key]['viatorName'] = $v['goods_name']
                        . ' - 共【' .count(array_filter(explode(',',$v['goods_image'])))
                        . '】张图片';
                    $correntViatorCodes[] = $value;
                    unset($viatorGoods[$k]);
                    break;
                }
            }
        }
        $correntViatorCodes = implode(',',$correntViatorCodes);

        return $this->success('success','',compact('viatorCodes','correntViatorCodes'));

    }
    //拉取viatorCode的远程图片
    public function pullViatorImagesByCodes(Request $request)
    {
        if(!$request->isPost()) return $this->error('请以POST方式提交');
        $viatorCodes = $request->post('viatorCodes','');
        $viatorCodes = explode(',',$viatorCodes);
        if(empty($viatorCodes)) return $this->error('请填写viatorCodes');
        foreach ($viatorCodes as $k=>$v){
            $viatorCodes[$k] = trim($v);
            $viatorCodesArr[$k] = '"'.trim($v).'"';
        }
        $order_expression = new Expression('field(code,'.implode(',',$viatorCodesArr).')');
        $viatorGoods = db('goods')->field('goods_id,goods_name,code,goods_image')->where([
            'show'=>2,
            'code'=>['in',$viatorCodes]
        ])->order($order_expression)->select();
        $data = (new Viator())->pullVitorImageByViatorCodes($viatorGoods,'code');
        if(!is_array($data)) return $this->error($data);
        //获取更新后的数据
        foreach ($data as $k=>$v) {
            $data[$k]['viatorName'] = $v['goods_name']. ' - 共【'. $v['countImage'] .'】张图片，拉取了【' . $v['countNewImage'] . '】张图片';
        }

        return $this->success('success','',compact('data'));
    }

    //判断是否超过拉取时间限制
    public function checkViatorGoodsByCityCache()
    {
        $isRunning = Cache::get('getViatorGoodsByCity');
        if(empty($isRunning)){
            return $this->success('succeess');
        }else{
            $limit_time = $isRunning - time();
            if($limit_time > 60){
                $mintue = intval( $limit_time/60 );
                $second = $limit_time - $mintue * 60;
                $limit_time = $mintue.'分'.$second.'秒';
            }else{
                $limit_time .= '秒';
            }
            return $this->error('限于服务器压力，切勿频繁操作！<br>接口仅允许每1小时可请求一次，请'. $limit_time.'后重试！');
        }
    }
}
